Explore Design Patterns----Factory mode

Source: Internet
Author: User

pattern Question: how can you easily and conveniently construct object instances without worrying about the details and complex process of constructing object instances?

Solution: Build a factory to create objects.

Realize:

< strong>, Introduction
    1) There is no factory era: if there is no industrial revolution, if a customer wants a BMW, the general practice is to create a BMW car, and then to use.
    2) Simple Factory mode: Later the Industrial Revolution occurred. Users do not have to create a BMW car. Because the customer has a factory to help him create a BMW. The factory can be built if you want a car. For example, want 320i series cars. The factory created this series of cars. That is, the factory can create products.
    3) Factory method Mode era: In order to meet customers, BMW series more and more, such as 320i,523i,30li Series A factory can not create all the BMW series. It is then separated from a number of specific factories. Each specific factory creates a series. That is, the specific factory class can only create a specific product. But the BMW factory is still an abstraction. You need to designate a specific factory to produce the car.
   4) Abstract Factory mode era: With the increasing demands of customers, BMW must be equipped with air-conditioning. So the factory started to produce BMW cars and needed air conditioners.
    Ultimately the customer just said to the BMW salesman: "I want 523i air-conditioning car, the salesman will give him 523i air-conditioned car directly." Instead of creating a BMW 523i air-conditioned car yourself.
    This is the Factory mode.

Second, classification
The factory model provides a transition interface for creating objects to isolate the concrete process masks for creating objects to achieve greater flexibility.
The factory model can be divided into three categories:
1) Simple Factory mode (easy Factory)
2) Factory mode (Factory method)
3) Abstract Factory mode (Factory)

Three, the difference
Factory method Mode:
An abstract product class that can derive a number of specific product classes.
An abstract factory class that can derive a number of specific factory classes.
Each specific factory class can only create an instance of a specific product class.
Abstract Factory mode:
Multiple abstract product classes, each abstract product class can derive multiple specific product classes.
An abstract factory class that can derive a number of specific factory classes.
Each specific factory class can create instances of more than one specific product class.
Difference:
The factory method pattern has only one abstract product class, and the abstract factory pattern has multiple.
Factory-mode-specific factory classes can only create instances of a specific product class, while abstract Factory mode may create multiple.

Four, simple Factory mode
Build a factory (a function or a class method) to create a new object.
Distribution Description Intro: From scratch. Customers create their own BMW cars and then use them.


public class BMW320 {public      BMW320 () {          System.out.println ("Manufacturing-->bmw320");      }  }    public class BMW523 {public      BMW523 () {          System.out.println ("Manufacturing-->bmw523");      }  }    public class Customer {public      static void Main (string[] args) {          BMW320 bmw320 = new BMW320 ();          BMW523 bmw523 = new BMW523 ();      }  }  

Customers need to know how to create a car, and the customer and the car are tightly coupled together. In order to reduce the coupling, there is the factory class, the creation of the BMW operation details are put into the factory, the customer directly use the factory to create a factory method, the introduction of the desired BMW model on the line, Without having to know the details of the creation. This is the Industrial Revolution: Simple Factory mode
That is, we create a factory class method to create new objects.


Product Category:

Abstract class BMW {public      BMW () {                }  } public    class BMW320 extends BMW {public      BMW320 () {          System . OUT.PRINTLN ("manufacturing-->bmw320");      }  }  public class BMW523 extends bmw{public      BMW523 () {          System.out.println ("Manufacturing-->bmw523");      }  }  

Factory class:

public class Factory {publicly      BMW createbmw (int type) {          switch (type) {case]                    :              return new BMW320 (); 
   
    case 523:              return new BMW523 ();            Default: Break              ;          }          return null;      }  }  
   

Customer class:

public class Customer {public      static void Main (string[] args) {          Factory Factory = new Factory ();          BMW bmw320 = FACTORY.CREATEBMW (+);          BMW bmw523 = FACTORY.CREATEBMW (523);      }  

The simple factory model is also called the Static factory method mode. Renaming can tell that this pattern must be simple. The purpose of its existence is simple: Define an interface for creating objects.
Let's take a look at its composition:
1) Factory class role: This is the core of this model, contains certain business logic and judgment logic, used to create the product
2) Abstract Product role: It is generally the product of the specific inheritance of the parent class or implementation of the interface.
3) Specific product roles: the object created by the factory class is an instance of this role. Implemented in Java by a concrete class.

Below we analyze the Simple Factory mode from the opening and closing principle (open for expansion; closed for modification). When customers no longer meet the existing model of the car, want a fast new type of car, as long as the car conforms to the abstract product formulation contract, so long as the notice factory class know can be used by customers. So for the part of the product, it is in accordance with the open and closed principle, but the factory part seems to be not ideal, because each added a new type of vehicle, to add the corresponding creation of business logic in the Factory class (CREATEBMW (int type) method needs to add case), this is obviously against the open and closed principle. It can be imagined that the introduction of new products, factory class is very passive. For such a factory class, we call it the Almighty class or the God class.
Our example is the simplest case, and in practical applications it is possible that the product is a multi-layered tree structure. Since there is only one factory class in the simple factory model that corresponds to these products, this may make our God tired and tired of our programmers.
So the factory method model as Savior appeared. The factory class is defined as an interface, and each new type of vehicle is added to the implementation of the plant class, so that the design of the plant can be expanded without having to modify the original code.

< strong> Five, factory method mode  
        Factory method mode removes the static property of the factory method in the simple Factory mode so that it can be inherited by the quilt class. The pressure to concentrate on factory methods in a simple factory model can be shared by different factory subclasses in the factory method model.  
Factory method pattern composition:  
       1) Abstract Factory role: This is the core of the factory method pattern, which is independent of the application. is the interface that the specific factory role must implement or the parent class that must inherit. In Java it is implemented by an abstract class or interface.  
      &NBSP;2) Specific factory role: It contains code that is relevant to the specific business logic. Called by the application to create an object that corresponds to a specific product.  
       3) abstract product role: It is the parent of a specific product inheritance or an interface implemented. In Java, there are generally abstract classes or interfaces to implement.  
       4) specific product roles: the object created by the specific factory role is an instance of this role. Implemented in Java by a specific class.  
        Factory method patterns use multiple subclasses that inherit from the abstract factory role to replace the "God Class" in simple Factory mode. As mentioned above, this shares the pressure of the object, and this makes the structure flexible--when a new product is produced, it can be used by the customer as long as it is generated by the contract provided by the abstract product role and the abstract factory role, without having to modify any existing code. We can see that the structure of the factory role is also in line with the closed principle!  

Product Category:

Abstract class BMW {public      BMW () {                }  } public  class BMW320 extends BMW {public      BMW320 () {          System . OUT.PRINTLN ("manufacturing-->bmw320");      }  }  public class BMW523 extends bmw{public      BMW523 () {          System.out.println ("Manufacturing-->bmw523");      }  }  


To create a factory class:

Interface FACTORYBMW {      BMW createbmw ();  }    public class FactoryBMW320 implements factorybmw{        @Override public      BMW320 createbmw () {            return new BMW320 () ;      }    }  public class FactoryBMW523 implements FACTORYBMW {      @Override public      BMW523 createbmw () {            return new BMW523 ();      }  }  

Customer class:

public class Customer {public      static void Main (string[] args) {          FactoryBMW320 factoryBMW320 = new FactoryBMW320 () ;          BMW320 bmw320 = FACTORYBMW320.CREATEBMW ();            FactoryBMW523 factoryBMW523 = new FactoryBMW523 ();          BMW523 bmw523 = FACTORYBMW523.CREATEBMW ();      }  

The factory method pattern seems to have been perfectly wrapped in the creation of objects, allowing the client to process only the interfaces provided by the abstract product role, but to multiply the number of objects. When the product category is very long, there will be a large number of corresponding plant objects, which is not what we want.
VI. Abstract Factory mode
As customers become more demanding, BMW needs to be equipped with air conditioning. So the factory started to produce BMW cars and configure the air conditioning needed. At this time the factory has two series of products: BMW car and air-conditioning.
Abstract Factory mode and factory method mode I read a lot of blogs and understand it a little differently, and I've written an example of what I think is the right understanding.
Here is a section from http://blog.csdn.net/zhengzhb/article/details/7359385 that explains the abstract factory pattern, and I feel quite clear, explaining the concept of the abstract factory pattern, But the code in his original version of the implementation of some mismatch, I understand, or with the front BMW 320 and BMW 523 configuration of different models of air Conditioning example wrote the following code, just my understanding, if you see here, some confusion, you can find some other articles to look at.

Abstract Factory mode is an upgraded version of the factory method pattern that is used to create a set of related or interdependent objects. The difference between him and the factory method pattern is that the factory method model is for a product hierarchy, while the abstract factory model is for multiple product hierarchy structures. In programming, typically a product structure is represented as an interface or abstract class, that is, all products provided by the factory method pattern are derived from the same interface or abstract class, and the products provided by the abstract factory schema are derived from different interfaces or abstract classes.

In the abstract factory model, there is a product family concept: the so-called product family, refers to the different products in the hierarchical structure of the functions associated with the family of products. The abstract factory model provides a series of products that form a product family, while the factory approach provides a range of products called a hierarchical structure. We still use the example of producing cars to illustrate the difference between them.

Abstract Factory mode code:

Car and model  abstract class BMW {public      BMW () {                }  } public  class BMW320 extends BMW {public      BMW320 ( {          System.out.println ("Manufacturing-->bmw320");}  }  public class BMW523 extends bmw{public      BMW523 () {          System.out.println ("Manufacturing-->bmw523");      }  }    Air conditioning and model public  class Aircondition {public      aircondition () {                }  } public  class Airconditiona Extends aircondition{public      Airconditiona () {          System.out.println ("Manufacturing-->airconditiona");      }  }  public class Airconditionb extends aircondition{public      airconditionb () {          System.out.println ("Make- Airconditionb ");      }  }  

To create a factory class:

Create a factory interface public interface FACTORYBMW {BMW createbmw_a ();      BMW Createbmw_b ();      Aircondition Createaairconditiona ();  Aircondition createaairconditionb (); }//BMW 320 series, production configuration A, b two air-conditioning models of 320 car public class FactoryBWM320 implements factorybmw{@Override public BMW32          0 createbmw_a () {//TODO auto-generated Method Stub Createaairconditiona ();      return new BMW320 (); } @Override Public BMW320 createbmw_b () {//TODO auto-generated method stub Createaairconditi          OnB ();      return new BMW320 (); } @Override Public Aircondition Createaairconditiona () {//TODO auto-generated method stub re      Turn new Airconditiona ();          } @Override Public Aircondition createaairconditionb () {//TODO auto-generated method stub      return new Airconditionb (); }}//BMW 523 series, production configuration A, b two air-conditioning models of 523 car public class FactoryBWM523 implements FACTORYBMW {@OverriDe public BMW523 createbmw_a () {//TODO auto-generated Method Stub Createaairconditiona ();      return new BMW523 (); } @Override Public BMW523 createbmw_b () {//TODO auto-generated method stub Createaairconditi          OnB ();      return new BMW523 (); } @Override Public Aircondition Createaairconditiona () {//TODO auto-generated method stub re      Turn new Airconditiona ();          } @Override Public Aircondition createaairconditionb () {//TODO auto-generated method stub      return new Airconditionb ();   }    }

Customer:

public class Customer {public      static void Main (string[] args) {                    //want Type a air-conditioner BMW          FactoryBWM320 factorybwm320_ A = new FactoryBWM320 ();          BMW320 bmw320_a = Factorybwm320_a.createbmw_a ();                    Want B-type air-conditioner BMW          FactoryBWM320 factorybwm320_b = new FactoryBWM320 ();          BMW320 bmw320_b = Factorybwm320_b.createbmw_b ();                    Want A-type air-conditioning BMW 523          FactoryBWM523 factorybwm523_a = new FactoryBWM523 ();          BMW523 bmw523_a = Factorybwm523_a.createbmw_a ();                    Want B-type air-conditioning BMW 523          FactoryBWM523 factorybwm523_b = new FactoryBWM523 ();          BMW523 bmw523_b = Factorybwm523_b.createbmw_b ();      }  }  

Summarize:

Whether it's a simple factory model, a factory method model, or an abstract factory model, they all belong to the factory model and are very similar in form and feature, and their ultimate goal is to understand the decoupling. In use, we don't have to care whether this pattern is a factory method or an abstract factory pattern, because the evolution between them is often elusive. Often you will find that the factory method is clearly used, when the new requirements come, slightly modified, adding a new method, because the products in the class constitute a different hierarchical structure of the product family, it becomes an abstract Factory mode, and for the abstract factory model, when the reduction of a method of the provided products no longer constitute the product family, It evolved into a factory method model.




Explore Design Patterns----Factory mode

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.