.NET design pattern (2): Factory Method pattern

Factory method model (Factory Method Pattern)

Introduction:
In simple factory pattern , we mentioned, the plant model method is simple factory pattern extending, it belongs to create patterns of design Gof23 design patterns. It remains to solve the problem in software design and create objects related. It can change to better handle customer needs.

Introducing
us to continue for " new new " problems, we have a simple factory pattern , the work of instantiating objects postponed to a factory class responsible for creating the object, so that, in case we known in advance, according to our needs create a dynamic product category. However, we predict is limited, customers change may be unlimited. So, there is a problem, once the customer changes beyond our foreknowledge, we must modify our source code. This design pattern is not allowed, how to do it? Factory Method pattern is to solve such problems.
Problem: Create a concrete factory working class can not meet our requirements, and job creation has changed
Solutions: Where is change, where package. The specific plant encapsulated.

Define
the factory method pattern, also known as the factory model, also known as virtual constructor (Virtual Constructor) mode or multi-mode factory state (Polymorphic Factory), the factory method pattern, the parent is responsible for defining the public interface to create objects, and then subclass is responsible for generating a particular object, the aim is to delay class instantiation operator to subclasses completed, i.e., to decide whether to instantiate subclasses (create) which class.

Intention
to define a user interface to create an object, but let subclasses decide which class to instantiate technology, the factory method pattern to instantiate a class delay to its subclasses.

Participants

  • Abstract product role (Product)
    product definition Interface
  • Role of specific products (ConcreteProduct)
    to implement the interface Product specific product category
  • Abstract Factory role (Creator)
    Statement factory method (FactoryMethod), to return a product
  • Real factory (ConcreteCreator)
    examples of the realization FactoryMethod factory method, called by the client to return a product

Factory Method pattern UML diagram of
FIG factory methods UML

an example of real life
in order to facilitate understanding, I still wear clothes an example of respect move. This example is a simple factory pattern that example is somewhat different.
It is said that there is a Qing Dynasty emperor very extravagant dress, each garment ( specific product category ) by a maid ( concrete factory class dedicated), so that, each additional clothes ( specific product category ), on a per cent more ladies ( concrete factory class ), but their duties, independently of each other. Emperor reason to do so, because it is for clothes, scalability is very strong ().

Analysis
functions implemented: according to the requirements of the emperor, dynamic creation (pick up by the ladies) specific products that already exist (clothes), if the emperor's too demanding, these clothes are not, just add a maid, a clothes We will be able to meet his request. Each is responsible only for the ladies A garment (high cohesion), to add a garment, for all previous and clothes for ladies, will not be affected (design mode desired). Here, the problem is not understood factory method pattern can be resolved and applied? Ha ha. . You must be thinking, flexibility than simple factory pattern now. .

Abstract Factory role Codes

 . 1 namespace  FactoryMethod
 2 {  . 3 /// <Summary>  . 4 ///  abstract factory class that defines the interface to the product  . 5 /// </ Summary>  . 6 public interface  IFactory The  . 7 {  . 8         iCoat CreateCoat ();  . 9     } 10 }
     
    
     

     
    


Abstract Product Code role

 . 1 namespace  FactoryMethod
 2 {  . 3 /// <Summary>  . 4 ///  abstract class products  . 5 /// </ Summary>  . 6 public interface  iCoat  . 7 {  . 8 void  ShowCoat ();  . 9     } 10 }
     
    
     

     
    
        

Concrete factory Role Code

 1 namespace FactoryMethod
 2{
 3    /// <summary>
 4    /// 具体工厂类:用于创建商务上衣类
 5    /// </summary>

 6    public class BusinessFactory:IFactory
 7    {        
 8        public ICoat CreateCoat()
 9        {
10            return new BusinessCoat();
11        }

12    }

13
14    /// <summary>
15    /// 具体工厂类,用于创建时尚上衣
16    /// </summary>

17    public class FashionFactory : IFactory
18    {
19        public ICoat CreateCoat()
20        {
21            return new FashionCoat();
22        }

23    }

24}

具体产品角色代码

 1 namespace FactoryMethod
 2{
 3    /// <summary>
 4    /// 具体产品类,商务上衣类
 5    /// </summary>

 6    public class BusinessCoat:ICoat
 7    {
 8        public void ShowCoat()
 9        {
10            Console.WriteLine("这件是商务上衣");
11        }

12    }

13
14    /// <summary>
15    /// 具体产品类,时尚上衣类
16    /// </summary>

17    public class FashionCoat : ICoat
18    {
19        public void ShowCoat()
20        {
21            Console.WriteLine("这件是时尚上衣");
22        }

23    }

24}

25

客户端代码

 1 namespace FactoryMethod
 2{
 3    /// <summary>
 4    /// 客户端代码
 5    /// </summary>

 6    class Client
 7    {
 8        static void Main(string[] args)
 9        {
10            //为了方便以后修改,将工厂类的类名写在应用程序配置文件中
11            string factoryName = ConfigurationManager.AppSettings["FactoryName"];
12          
13            IFactory factory = (IFactory)Assembly.Load("ConcreteFactory").CreateInstance("FactoryMethod." + factoryName);
14            
15            ICoat coat = factory.CreateCoat();
16            //显示你要的上衣
17            coat.ShowCoat();
18        }

19    }

20}

客户端代码需要注意的两个地方:
1,把具体工厂类类名称写在了应用程序配置文件中,方便修改
2,用到了反射,利用.NET提供的反射可以根据类名来创建它的实例,非常方便


由反射想到的:
下面这一段内容不是计划要写的。
如果在具体工厂中,每次new的对象都是一个,而且这些类是继承自抽象产品接口的,那么我们用简单工厂模式也 可以实现动态的增加具体产品类。这样来做,在简单工厂模式中最核心的部分----工厂类不要根据传来的条件去动态创建产品类,利用反射机制去创建。把要实 例化的类名放在应用程序配置文件中,呵呵。。这样利用.NET特有的反射就可以用简单工厂模式解决更多的问题了,工厂方法模式的一部分问题也是可以通过 “这样的简单工厂模式”解决的,在需要增加具体产品类时,不用增加具体工厂,是不是简单一些呀。下去试一下。。。

优点:

  • 基于工厂角色和产品角色的多态性设计是工厂方法模式的关键。它能够使工厂可以自主确定创建何种产品对象。而且如何创建一个具体产品的细节完全封装在具体工厂内部,符合高内聚,低耦合。
  • 在系统中加入新产品时,无需修改抽象工厂和抽象产品提供的接口,无需修改客户端,也无需修改其他的具体工厂和具体产品,很好的利用了封装和委托。

缺点:

  • 在添加新产品时,需要编写新的具体产品类(其实这不算一个缺点,因为这是不可避免的),要增加与之对应的具体工厂类。

应用情景:

  • 类不知道自己要创建哪一个对象时
  • 类用它的子类来指定创建哪个对象
  • 当类将创建对象的职责委托给多个帮助子类中的某一个,并且你希望将哪一个帮助子类是代理者这一信息局部化的时候  

Factory Method pattern in application ASP.NET HTTP channel, TerryLee in his essay file in very well written, it is recommended to take a look.

Reference material

  • "Design Patterns in layman's language (C # / Java version)," Tsinghua University Press 
  • Webcast the MSDN  C # object-oriented design patterns Talk about Li Jianzhong teacher

Download source:
             http://files.cnblogs.com/anlyren/FactoryMethod.rar

References to: http://www.cnblogs.com/anlyren/archive/2008/01/26/factory_method.html


Reproduced in: https: //www.cnblogs.com/zhangchenliang/archive/2011/08/17/2143044.html

Guess you like

Origin blog.csdn.net/weixin_34403693/article/details/93494972