design mode (i) Factory mode factory (create type)

Source: Internet
Author: User

Design mode one Factory mode factory

In object-oriented programming, the most common approach is to create an object instance with a new operator, which is used to construct an object instance. In some cases, however, the new operator's direct generation of objects poses some problems.

For example, the creation of many types of objects requires a series of steps: You may need to calculate or get the initial set of objects; Select which child object instance to generate; Or, you must first generate some accessibility objects before you can generate the objects you need. In these cases, the creation of a new object is a "process", not just an operation, like a gear drive in a large machine.

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

How to solve: Build a factory to create objects.

Realize:

First, Introduction
1) There is no factory era: if there is no industrial revolution, suppose 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 will be built if you want a car. For example, want a 320i series car. 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 cannot create all of the BMW series. It is then separated by a number of detailed factories. Each detailed factory creates a series. That is, the detailed factory class can only create a detailed product.

But the BMW factory is still an abstraction. You need to designate a detailed factory to produce a car.
4) Abstract Factory mode era: With the increasing demands of customers, BMW must be equipped with air-conditioning.

Also this air conditioner must be used accordingly to the series vehicle talents. So the factory started to produce BMW cars and the air conditioning needed.


         Finally, the customer just wanted to say to the BMW salesman: "I want 523i air-conditioned car, the salesman will give him 523i air-conditioned car directly." Instead of creating a BMW 523i air-conditioned car yourself.
    (I just give a sample, said BMW configuration air conditioning is for example, even a little bit, which car and air conditioning must be appropriate to use AH)
      This is the Factory mode.
II, category  
          Factory mode is primarily to provide a staging interface for creating objects. In order to isolate the detailed 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 method mode (Factory methods)  
3) Abstract Factory mode (abstract Factory)  
         These three modes are progressively abstracted from top to bottom, and more general.  
        gof divides the factory model into two categories in design mode: The Factory method mode (Factory method) with abstract Factory mode (Factory).

The simple Factory is seen as a special case of the factory method pattern, which is grouped into one category.
Three, the difference
Factory method Mode:
An abstract product class. The ability to derive multiple detailed product classes.
An abstract factory class that can derive multiple detailed factory classes.
Each detailed factory class can only create an instance of a detailed product class.
Abstract Factory mode:
Multiple abstract product classes. Each abstract product class can derive multiple detailed product classes.
An abstract factory class. The ability to derive multiple detailed factory classes.
Each detailed factory class is able to create instances of more than one detailed product class.
Difference:
The factory method pattern has only one abstract product class, and the abstract factory pattern has multiple.


The detailed factory class of the factory method pattern can only create an instance of a detailed product class. Abstract Factory mode can create multiple.
Both are available.


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.



<?php/** * Car Series * */class bwm320{function __construct ($pa) {}}class bmw523{   function __construc ($PB) {}}/** *  * Customers create their own BMW */class Customer {   function createBMW320 () {       return new BWM320 ();   }   function createBMW523 () {       return 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 can be, 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:

<?php/** * Car Series * */abstract Class bwm{    function __construct ($PA) {    }}class BWM320 extends bwm{    functio n __construct ($pa) {    }}class BMW523 extends bwm{   function __construc ($PB) {   }}

Factory class:

/** *  * Factory Create car */class Factory {    static function  CREATEBMW ($type) {        switch ($type) {case          :             return new BWM320 ();          Case 523:             return new BMW523 ();        //....   }}

Customer class:

/** *  * Customer through the factory to obtain the car */class customer {    private $BMW;    function GETBMW ($type) {        $this?-> BMW =  factory::createbmw ($type);    }}


The simple factory model is also called the Static factory method mode. Renaming can see that this pattern must be very easy. The purpose of its existence is very easy: 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 inference logic.
2) Abstract Product role: it is usually the parent class for detailed product inheritance or an implemented interface.
3) Detailed Product role: the object created by the factory class is an instance of this role. Implemented in Java by a detailed class.

Below we analyze the Simple Factory mode from the opening and closing principle (open for expansion; closing the change). When customers no longer meet the existing model of the car, want a new type of fast speed car. Only this kind of car conforms to the contract of abstract product formulation. Then just tell the factory class that you can be used by the customer. So for the part of the product, it is in accordance with the opening and shutting principle. But the factory part seems to be less than ideal.since each new type of vehicle is added, the corresponding creation business logic (CREATEBMW ($type) method needs to be added in the factory Class), which is clearly a violation of the opening and closing principle。 Can be imagined for the addition of new products. The factory class is very passive. For this kind of factory class. We call it the Almighty class or the God class.
Our example is the simplest case, and in practical applications it is very likely that the product is a multi-layered tree structure. Because there is only one factory class in the simple factory model to correspond to these products. So this might put our God very tired and very tired of us these procedural apes: (
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 corresponding factory class of the vehicle type, so that the plant can be expanded without having to change the original code.


Five, factory method mode
The factory method mode removes the static properties of the factory method in the simple Factory mode. Makes it possible for the quilt class to inherit. The pressure to concentrate on factory methods in a simple factory model can be shared by different factory subclasses in the factory method model.
The factory method pattern consists of:
1) Abstract Factory role: This is the core of the factory method pattern, which is independent of the application. is the interface that the detailed factory role must implement or the parent class that must inherit.

In Java it is implemented by an abstract class or interface.


2) Detailed factory role: it contains code related to detailed business logic. Called by the application to create the appropriate detailed product for the object.


3) Abstract Product role: It is the parent of detailed product inheritance or an interface implemented. In Java, there are generally abstract classes or interfaces to implement.
4) Detailed Product role: the object created by the detailed factory role is an instance of this role.

Implemented in Java by a detailed class.


The factory method pattern uses multiple subclasses that inherit from the abstract factory role to replace the "God Class" in the simple factory pattern. As said above. This will share the pressure on the subject. And this makes the structure flexible-when a new product is created, it can only be generated by the contract provided by the abstract product role, the abstract factory role, and then be used by the customer. Without having to change whatever code is already there. Can see the structure of the factory role is also in line with the principle of open and close!


The code is as follows:

Product Category:

<?php/** * Car Series * */abstract Class bwm{function __construct ($pa) {}}class BWM320 extends bwm{function __construct ($PA) {}}class BMW523 extends bwm{   function __construc ($PB) {}}


To create a factory class:

/** * Create a factory interface * */interface FACTORYBMW {        function createbmw ();}/** *  * Create BWM320 car */class FactoryBWM320 Implement s FACTORYBMW {   function  createbmw ($type) {      return new BWM320 ();}   } /** *  * Create BWM523 car */class FactoryBWM523 implements FACTORYBMW {   function  createbmw ($type) {      return new BMW523 ();   }}


Customer class:

/** *  * Customers get car */class customer {   private $BMW;   function  GETBMW ($type) {      switch ($type) {case        :           $BWM = new FactoryBWM320 ();           return $BWM 320->CREATEBMW ();        Case 523:           $BWM 523 = new FactoryBWM523 ();           return $BWM 320->CREATEBMW ();            //....      }  }}


Can see the increase in factory methods. The number of objects increases exponentially. When the product variety is many, there will be a large number of corresponding factory objects, which is not what we want. It is assumed that such a situation cannot be avoided. The ability to consider the combination of a simple factory model and a factory method model to reduce the factory class is achieved by using a simple factory pattern for similar species on the product tree (usually brothers in the leaves of the tree).


Factory Method Summary:
The factory method pattern seems to have been perfectly wrapped in the creation of objects, allowing only the interfaces provided by the abstract product role to be processed in the client program. Do we have to be in the code all over the factory? It doesn't have to be big. Perhaps you can consider using the factory method mode in the following situations:
1) When the client program does not need to know to use the object creation process.
2) There is a possibility that the object used by the client is changing, or it is not known which detailed object to use at all.


The simple Factory mode and factory method mode really avoids the code changes? No. In the simple factory model, the addition of new products changes the inference statements in the factory role, while in the factory method mode. Either leave the judgment logic in the abstract factory role. Either write the detailed factory role to death (as in the example above) in the client program. And the change of the Product object creation condition is bound to cause the changes of the factory role.
In the face of this situation, we are able to use the reflection mechanism:

Class Customer {     private $BMW;     function  GETBMW ($type) {         $class = new Reflectionclass (' FACTORYBWM '. $type);//Create a reflection class of ' Factorybwm ' class            $ Instance  = $class->newinstanceargs ();//equivalent to instantiating ' FACTORYBWM '. $type class            return $instance->CREATEBMW ();        or direct          /**         * $instance = new ' Factorybwm '. $type ();         * Return $instance->CREATEBMW ();         */    }}

VI. Abstract Factory mode
As customers demand more and more, the BMW car needs to be equipped with air conditioning. So the factory started to produce BMW cars and the air conditioning needed for configuration. At this time the factory has two series of products: BMW and air-conditioning. BMW must use the appropriate air-conditioning capabilities. This time the use of a car factory and an air-conditioning plant can not meet our needs, we must confirm the car and the corresponding relationship between the air conditioning.

So the car factory is connected with the air-conditioning factory.

So there is the abstract factory pattern.
To be able to say, the difference between the abstract factory pattern and the factory method pattern is the complexity of the objects that need to be created. and the abstract factory model is the most abstract and most general of the three.
Abstract Factory mode is intended to provide the client with an interface to create product objects in multiple product families. Also, use the abstract Factory mode to meet the criteria:
1) There are multiple product families in the system. And the system can only consume one family of products at a time.
2) products belonging to the same product family for their use.
The various roles of the abstract factory pattern (as with the Factory method):
1) Abstract Factory role: This is the core of the factory approach model. It is independent of the application. is the interface that the detailed factory role must implement or the parent class that must inherit.

In Java it is implemented by an abstract class or interface.
2) Detailed factory role: it contains code related to detailed business logic. Called by the application to create the appropriate detailed product for the object.
3) Abstract Product role: It is the parent of detailed product inheritance or an interface implemented.


4) Detailed Product role: the object created by the detailed factory role is an instance of this role.

Its structure:



Examples of our sample:


Code:

Product Category:

<?php/** * Car Series and model * */abstract class  Bwm{}class BWM523 extends  BWM {}class BWM320 extends  BWM {}/** * air conditioning * */abstract class Aircondition{}class airconditionBWM320  extends Aircondition {}class airconditionBWM52 extends aircondition {}
To create a factory class:

/** * Create a factory interface * */interface FACTORYBMW {      function createbmw ();      function Createairc (); }/** *  * Create BWM320 car */class FactoryBWM320 implements FACTORYBMW {    function  createbmw () {    return new BWM320 ();} function  Createairc () {//air conditioner    return new airconditionBWM320 ();}} /** *  * Create BWM523 car */class FactoryBWM523 implements FACTORYBMW {    function  createbmw () {    return new BWM523 ();} function  Createairc () {    return new airconditionBWM523 ();}}
Customer:

/** *  * Customers get car */class customer {   private $BMW;   Private $airC;   function  GETBMW ($type) {       $class = new Reflectionclass (' FACTORYBWM '. $type);//Create a reflection class of person this class          $ Instance  = $class->newinstanceargs ();//equivalent to the instance person category          $this->bmw =  $instance->createbmw () ;       $this->airc =  $instance->createairc ();}   }


Design mode (i) Factory mode factory (create type)

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.