Design pattern in a comprehensible way--factory method Mode (Factory methods)

Source: Internet
Author: User

Introduced
In the simple factory model, we mentioned that the factory method pattern is an extension of the simple factory pattern, which belongs to the design pattern in the Gof23 design pattern. It still solves the problem of creating objects in software design. It can better handle the change of customer's demand.

Introduced
We continue to say "new", in the simple factory model, we defer the work of instantiating objects to a factory class that is specifically responsible for creating objects, so that we can dynamically create product classes based on our needs in advance of our prediction. However, our forecast is limited, and the customer's change may be limitless. So, there is a problem, once the customer changes beyond our prediction, we have to modify our source code. This is not allowed in the design mode, how to do? The factory method model solves this kind of problem.
Problem: the creation of specific factory classes does not meet our requirements, the creation of the work has changed
Solution: Where to change, where to package. Encapsulate the specific factory.

Defined
The factory method pattern is also called the Factory mode, which is called the virtual Constructor mode or the Polymorphic Factory mode (polymorphic Factory), in the factory method pattern, the parent class is responsible for defining the public interface for creating the object, while the subclass is responsible for generating the concrete object , the purpose of this is to defer instantiation of the class to the subclass, which is the subclass that determines which class should be instantiated (created).
The Factory mode mode (Factory method) defines an interface for creating objects, allowing subclasses to decide which class to instantiate. The factory method defers the instantiation of a class to a subclass.

Intention
Defines an interface for user-created objects, allowing subclasses to decide which class to instantiate, and the factory method pattern to defer instantiation of a class to its subclasses.

Participants
Abstract product Role (product): Defines the interface for the products
Specific product roles (CONCRETEPRODUCT): specific product classes that implement Interface product
Abstract Factory Role (Creator): Claims Factory Method (FactoryMethod), returns a product
Real Factory (Concretecreator): Implements FactoryMethod factory method, called by customer, returns an instance of a product
Factory method Mode UML diagram

Real-life examples
To make it easy for everyone to understand, I still have an example of wearing clothes. This example is somewhat different from that in the simple factory model.
It is said that the Qing dynasty had an emperor dressed very extravagant, each kind of clothing (specific product category) by a maid (Specific factory class) dedicated to the responsibility, so that each additional clothing (specific product category), will be more than a maid (specific factory), but they accountability, do not affect each other. The emperor did this because the scalability was very strong in the case of wearing clothes.

Analysis
Implementation of the function: according to the requirements of the emperor, dynamic Creation (by the maid to get) the specific products (clothes) already exist, if the emperor's requirements are too harsh, the clothes have not yet, only need to add a maid, a clothes can meet his requirements. Each maid is responsible for only one kind of clothes (high cohesion), to add a kind of clothes, for all the former maid and clothes, will not be affected (the design model is expected). Speaking of which, do you understand the problem that the factory method model solves and its application? Oh.. You must be thinking, it's more flexible than a simple factory model.
System structure

ICoat.cs

namespace factorymethod{    //      <summary>///Abstract products///       </summary>public    interface  icoat    {          void  showcoat ();    }}

IFactory.cs

namespace factorymethod{    ///<summary>///      Abstract Factory class,    defining the interface of the product /// </summary>     Public Interface ifactory    {        icoat createcoat ();    }}

FashionCoat.cs

 using   System;  namespace   factorymethod{ <summary>  ///  specific product category, Fashion top class  /// </SUMMARY>  public  class   Fashioncoat:icoat {public  void   Showcoat () {Console.WriteLine ( "  This is a fashion blouse.          ); }    }}

BusinessCoat.cs

 using   System;  namespace   factorymethod{ <summary>  ///  specific products, business tops category  /// </SUMMARY>  public  class   Businesscoat:icoat {
    public  void   Showcoat () {Console.WriteLine ( "  This is a business blouse          ); }    }}

FashionFactory.cs

namespace factorymethod{    ///<summary>//      Specific factory class for creating    stylish tops /// </summary>     Public class fashionfactory:ifactory    {        public  icoat createcoat ()        {            returnnew  Fashioncoat ();     }}}

BusinessFactory.cs

namespace factorymethod{          //<summary>///Specific factory class: Used to    create business top class /// </summary>     Public class businessfactory:ifactory    {        public  icoat createcoat ()        {            returnnew  Businesscoat ();     }}}

App.

<?XML version= "1.0" encoding= "Utf-8"?><Configuration>    <appSettings>        <AddKey= "Factoryname"value= "Fashionfactory"/>    </appSettings></Configuration>

Program.cs

usingSystem;usingSystem.Configuration;usingSystem.Reflection;namespacefactorymethod{classClient {Static voidMain (string[] args) {            //Businessfactory factory = new Businessfactory (); //to facilitate later modification, write the class name of the factory class in the application configuration file            stringFactoryname = configurationmanager.appsettings["Factoryname"]; Ifactory Factory= (ifactory) assembly.load ("FactoryMethod"). CreateInstance ("FactoryMethod."+factoryname); Icoat Coat=Factory.            Createcoat (); //show the top you wantcoat.            Showcoat ();        Console.ReadLine (); }    }}

Two places to note for client code:
1, the specific factory class name written in the application configuration file, easy to modify;
2, use of reflection, use. NET provides the ability to create an instance of it based on the class name, which is very convenient.

Advantages of the Factory method model
In the factory method model, the factory method is used to create the product that the customer needs, but also hides to the customer which specific product class will be instantiated this detail, the user only needs to care about the product corresponding factory, does not care about the creation detail, even does not need to know the specific product class the class name.
Polymorphism design based on plant roles and product roles is the key to the factory approach model. It enables the factory to determine which product objects are created autonomously, and the details of how to create the object are completely encapsulated inside a specific factory. The factory method pattern is also called the Polymorphic factory pattern because all the specific factory classes have the same abstract parent class.
Another advantage of using the factory method pattern is that when adding a new product to the system, it is not necessary to modify the interface provided by the abstract factory and the abstract product, without modifying the client, or modifying the other specific factories and specific products, as long as a specific factory and specific products can be added. In this way, the scalability of the system becomes very good, fully conform to the "open and close principle".

Disadvantages of the factory method model
When adding new products, we need to write the specific product classes, but also to provide the corresponding specific factory class, the number of classes in the system will increase in pairs, to a certain extent, increase the complexity of the system, there are more classes need to compile and run, will bring some additional overhead to the system.
Due to the scalability of the system, it is necessary to introduce the abstraction layer, which is used in the client code to define the abstraction layer, which increases the abstraction and difficulty of comprehension, and it may need to use the techniques of DOM, reflection and so on to increase the difficulty of the system implementation.

Mode applicable environment
You can use the factory method mode in the following situations:
A class does not know the class of the object it needs: In the Factory method mode, the client does not need to know the class name of the specific product class, only need to know the corresponding factory, the specific product object is created by the specific factory class; The client needs to know the factory class that created the specific product.
A class specifies which object to create by its subclasses: in the factory method pattern, for the abstract factory class, you only need to provide an interface to create the product, and its subclasses determine the object to be created, take advantage of the object-oriented polymorphism and the Richter substitution principle, when the program runs, the subclass object will overwrite the parent class object. This makes the system easier to scale.
Delegate the task of creating an object to one of several factory subclasses, which the client can use without having to care about which factory subclass creates a product subclass that is dynamically specified when needed, and stores the class name of the specific factory class in the configuration file or database.

Summary
The factory method mode, also known as the Factory mode, belongs to the class-creation pattern. In factory method mode, the factory parent is responsible for defining the public interface that creates the product object, while the factory subclass is responsible for generating the specific product object, which is intended to defer the instantiation of the product class to the factory subclass, i.e., the factory subclass to determine which specific product class should be instantiated.
The factory method pattern consists of four roles: An abstract product is an interface for defining a product, a super-type of object created by a factory method pattern, a common parent class or interface for a product object, a product that implements an abstract product interface, a specific product of a particular type is created by a specific factory, and often one by one corresponds The factory method is declared in the abstract factory to return a product, which is the core of the factory method pattern, and any factory class that creates objects in the schema must implement the interface; The factory is a subclass of the abstract factory class, implements the factory method defined in the abstract factory, and can be called by the customer to return an instance of a specific product class.
The factory method model is a further abstraction and generalization of the simple factory model. Due to the use of object-oriented polymorphism, the factory method pattern preserves the advantages of a simple factory model and overcomes its drawbacks. In the factory method model, the core factory class is no longer responsible for the creation of all the products, but rather the specific creation work to the subclass to do. This core class is only responsible for giving the interface that a specific factory must implement, not the details of the product class being instantiated, which allows the factory method pattern to allow the system to introduce new products without modifying the factory role.
The main advantage of the factory method pattern is that the new product class can be added without modifying the existing system, and the creation details of the product object are encapsulated, the system has good flexibility and expansibility, the disadvantage is that adding new products at the same time, the increase of the number of the system class increases, which increases the complexity of the system to some extent.
The application of the factory method pattern includes: A class that does not know the class of the object it needs, a class that specifies which object to create through its subclasses, and the task of creating the object to one of several factory subclasses, which the client can use without having to care about which factory subclass creates the product subclass, and then dynamically assigns it when needed.

Design pattern in a comprehensible way--factory method Mode (Factory methods)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.