(精华)2020年8月14日 C#基础知识点 23种设计模式(创建型模式---原型模式和工厂模式)

原型模式:对象创建不走构造函数

SingletonPrototype prototype = (SingletonPrototype)_SingletonPrototype.MemberwiseClone();//内存copy

工厂模式:顾名思义用的很多管理对象的创建

class Program
    {
        static void Main(string[] args)
        {
            try
            {
                {
                    //工厂方法+ 抽象--是必须全部实现的:方便扩展种族 但是不能扩展产品簇--倾斜性可扩展性设计
                    AbstractFactoryBase factory = new HumanFactoryAbstract();
                    IRace race = factory.CreatRace();
                    IArmy army = factory.CreateArmy();
                    IResource resource = factory.CreateResource();
                }
                {
                    AbstractFactoryBase factory = new UndeadFactoryAbstract();
                    IRace race = factory.CreatRace();
                    IArmy army = factory.CreateArmy();
                    IResource resource = factory.CreateResource();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.ReadLine();
        }
    }
    public abstract class AbstractFactoryBase
    {
        public abstract IRace CreatRace();
        public abstract IArmy CreateArmy();

        public abstract IResource CreateResource();
    }
    public class HumanFactoryAbstract : AbstractFactoryBase
    {
        public override IRace CreatRace()
        {
            return new Human();
        }
        public override IArmy CreateArmy()
        {
            return new HumanArmy();
        }
        public override IResource CreateResource()
        {
            return new HumanResource();
        }
    }
    public class UndeadFactoryAbstract : AbstractFactoryBase
    {
        public override IRace CreatRace()
        {
            return new Undead();
        }
        public override IArmy CreateArmy()
        {
            return new UndeadArmy();
        }
        public override IResource CreateResource()
        {
            return new UndeadResource();
        }
    }

你可能感兴趣的:(C#,c#)