jeudi 27 août 2020

Create a List of objects using Abstract Factory Pattern

I have a game with 2 types of characters, Hero and Monster. They will belong to one of the two following elements: Fire and Water. With the input choosing Fire or Water then choosing Hero or Monster creation. Output: Returns whether the object is created or not. I have developed it at the level of creating an object. I want to use List to create list of objects. What am I supposed to do with my code, because I really don't know where to put it

  • AbstractFactory
    public abstract class CharactersAbstractFactory
    {
        public abstract Hero CreateHero();
        public abstract Monster CreateMonster();
    }
  • ConcreteFactory
    class FireFactory: CharactersAbstractFactory
    {
        public override Hero CreateHero()
        {
            return new FireHero();
        }

        public override Monster CreateMonster()
        {
            return new FireMonster();
        }

  • AbstractProduct
 public abstract class Hero
    {
        protected int level = 1;
        protected int basicAttack = 50;
        public string Name;
        public Sect Sect;
        public Hero()
        {

        }
        public Hero(string name, Sect sect)
        {
            Name = name;
            Sect = sect;
        }
        public abstract void Create();

        public int Dame()
        {
            int dame = basicAttack * level;
            return dame;
        }
    }
    public enum Sect
    {
        ThieuLam,
        ThienVuong,
        NgaMy,
        YenMon
    }
  • Class Characters
    public class FireHero : Hero
    {
        public FireHero()
        {
        }

        public FireHero(string name, Sect sect) : base(name, sect)
        {
        }

        public override void Create()
        {
            Console.WriteLine("Create Hero with Fire Elements");
        }
    }
  • CharactersFactory
        public static CharactersAbstractFactory GetFactory(Elements elements)
        {
            switch (elements)
            {
                case Elements.Fire:
                    return new FireFactory();
                case Elements.Water:
                    return new WaterFactory();
                default:
                    Console.WriteLine("No elements");
                    return null;
            }
        }
  • Main
CharactersAbstractFactory factory = CharactersFactory.GetFactory(Elements.Fire);
Hero herofire = factory.CreateHero();
herofire.Create();
Monster monsterfire = factory.CreateMonster();
monsterfire.Create();

Aucun commentaire:

Enregistrer un commentaire