zoukankan      html  css  js  c++  java
  • 工厂方法模式

    动机(Motivation):
        在软件系统中,由于需求的变化,"这个对象的具体实现"经常面临着剧烈的变化,但它却有比较稳定的接口
        如何应对这种变化呢?提供一种封装机制来隔离出"这个易变对象"的变化,从而保持系统中"其它依赖的对象"不随需求的变化而变化。

    意图(Intent):
        定义一个用户创建对象的接口,让子类决定实例哪一个类。Factory Method使一个类的实例化延迟到子类。

    适用性:
        1.当一个类不知道它所必须创建的对象类的时候。
        2.当一个类希望由它子类来指定它所创建对象的时候。
        3.当类将创建对象的职责委托给多个帮助子类中的某个,并且你希望将哪一个帮助子类是代理者这一信息局部化的时候。

    具体实现在跳转页的下方,写了从简单工厂到工厂模式的演变,每个方法都需要学习,下方只是给出了工厂模式。(可以使工厂类进行封装)

     #region 创建接口
        interface Sender
        {
            void send();
        }
    
        //工厂接口
        interface IProduce
        {
            Sender produce();
        }
        #endregion
      #region 实现类
        class MailSender : Sender
        {
            public void send()
            {
                Console.WriteLine("this is Mail");
            }
        }
        class SmsSender : Sender
        {
            public void send()
            {
                Console.WriteLine("this is Sms");     
            }
        }
        #endregion
        #region 工厂类
        class MailFactory : IProduce
        {
            public Sender produce()
            {
                return new MailSender();
            }
        }
        class SmsFaCTORY : IProduce
        {
            public Sender produce()
            {
                return new SmsSender();
            }
        }
        #endregion

    与上方无关,静态工厂实现起来也很简单,如下

      class Factory
        {
            public static Sender MailSender()
            {
                return new MailSender();
            }
            public static Sender SmsSender()
            {
                return new SmsSender();
            }
        }
         static void Main(string[] args)
            {
                //工厂模式实现
                Sender mail = new MailSender();
                mail.send();
                //静态工厂模式实现
                Factory.SmsSender().send();
                Console.ReadKey();
            }

  • 相关阅读:
    Mini440之uboot移植之源码分析board_init_f(二)
    Mini440之uboot移植之源码分析uboot重定位(三)
    Mini440之uboot移植之实践DM9000支持(八)
    Mini2440裸机开发之DM9000
    Mini440之uboot移植之源码分析命令解析(五)
    Mini440之uboot移植之实践NOR启动(六)
    Mini440之uboot移植之实践NOR FLASH支持(七)
    mysql调优和SQL优化
    linux man手册使用相关问题
    关于ca以及证书颁发的一些事
  • 原文地址:https://www.cnblogs.com/ningxinjie/p/12220568.html
Copyright © 2011-2022 走看看