抽象工厂的一点学习

1.定义一个接口:人类,它可以有跑这样的一个动作(估且这么说吧)

 public interface IHuman
    {
        void Run();
    }

2.来一个男人和一个女人,让他们继承人类,当然了,要去实现Run()方法

public class Woman : IHuman
    {
        public Woman()
        {
            Console.WriteLine("The girl fall in love");
        }

        public void Run()
        {
            Console.WriteLine("There is a girl in the running");
        }
    }

    public class Man : IHuman
    {
        public Man()
        {
            Console.WriteLine("The guy fall in love");
        }

        public void Run()
        {
            Console.WriteLine("A guy with the girl behind");
        }
    }

3.下面我们来搭建加工厂模板

 public interface IFactory
    {
        /// <summary>
        /// 声明一个 GetMarried 返回 IHuman 实例
        /// </summary>
        /// <returns>返回 IHuman 实例</returns>
        IHuman GetMarried();
    }

    public class WomanFactory : IFactory
    {
        public IHuman GetMarried()
        {
            return new Woman();
        }
    }

    public class ManFactory : IFactory
    {
        public IHuman GetMarried()
        {
            return new Man();
        }
    }

4.写一个方法用来生成对应的加工厂

public class HumanFactory
    {
        public static IFactory CreateFacory(string factoryType)
        {
            Type t = Type.GetType(factoryType);
            return Activator.CreateInstance(t) as IFactory;

            //另一种方法创建实体工厂对象Assembly.Load(程序集名称).CreateInstance(命名空间.类名)
            //IFactory carFactory = System.Reflection.Assembly.Load("ConsoleApplication1").CreateInstance(factoryType) as IFactory;
            //return carFactory;
        }
    }

5.测试一下:

class Program
    {
        static void Main(string[] args)
        {
            #region demo1

            //ConsoleApplication1.ManFactory可以写到配置文件中,此处略
            IFactory humFactory = HumanFactory.CreateFacory("ConsoleApplication1.ManFactory");
            IHuman hyman = humFactory.GetMarried();
            hyman.Run();
            Console.ReadKey();

            #endregion           
        }
    }

效果:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值