C#--设计模式--工厂模式

 /// <summary>
    /// 工厂模式
    /// 工厂模式是将对象的创建与上游使用方,进行分离。通过factory对象来创建。
    /// 通过factory对象来创建,通过配置信息,进行创建对象,就是工厂根据采购清单生产商品一样
    /// 1.通过配置文件来配置对象信息。
    /// 2.通过配置信息+反射来进行对象的创建。
    /// 3.上游对象不需要关心对象的创建过程。
    /// </summary>
    class Program
    {
        static void Main(string[] args)
        {
            ///1.直接创建对象方式
            ///对象创建在上游[主程序]已经确定,不能进行分离。
            InitMethods1();
            ///2.通过工厂对象创建对象
            InitFactory();
            Console.Read();
        }

        private static void InitFactory()
        {
            IAnimal animal = ObjectFactory.CreateInit<IAnimal>();
            animal.Sleep();
        }

        private static void InitMethods1()
        {
            IAnimal cat = new Cat();
            IAnimal dog = new Dog();
            cat.Sleep();
            dog.Sleep();
        }
    }

创建动物(IAnimal)接口:


    public interface IAnimal
    {
        void Sleep();
    }

创建猫类(Cat),继承IAnimal


    public class Cat : IAnimal
    {
        public void Sleep()
        {
            Console.WriteLine("当前对象{0}",this.GetType());
        }
    }

创建dog类,继承Ianimal

 public class Dog : IAnimal
    {
        public void Sleep()
        {
            Console.WriteLine("当前对象{0}",this.GetType());
        }
    }

ObjectFactry对象,用于根据XML配置信息创建对象


    class ObjectFactory
    {
        /// <summary>
        /// 通过工厂对象创建对象
        /// </summary>
        /// <returns>当前实例对象</returns>
        static string config =  ConfigurationManager.ConnectionStrings["factoryConfig"].ConnectionString;
        public static T CreateInit<T>()
        {
            try
            {
                string dllName = config.Split(',')[0];
                string className = config.Split(',')[1];
                Assembly assembly = Assembly.Load(dllName);
                Type type = assembly.GetType(className);
                return (T) Activator.CreateInstance(type);
            }
            catch (Exception)
            {
                throw new Exception("Class Exception");
            }
        }
    }

XML:

<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.1" />
    </startup>
  <connectionStrings>
    <add name="factoryConfig" connectionString="FactoryLibrary,Factory.Cat"/>
    <add name="factoryConfig1" connectionString="FactoryLibrary,Factory.Dog"/>
    <!---->
  </connectionStrings>
</configuration>

运行结果如下图:

如果将XML配置文件修改为<add name="factoryConfig" connectionString="FactoryLibrary,Factory.Dog"/>,运行结果如下:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值