The Factory mode of Java design mode

Source: Internet
Author: User

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 directly generates the object, causing 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 settings of the object; Select which child object instance to generate; Or, you must generate some accessibility objects before you can build 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?

Solution : Build a factory to create objects

Realize:

First, 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 of 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.

In the end, the customer just said 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.

This is the factory model.

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)

These three modes are progressively abstracted from top to bottom and more general.
In design mode, GOF divides the factory model into two categories: The Factory method Model (Factory) and the Abstract Factory mode (abstraction 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 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.
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.

 Public BMW320 {    BMW320 () {       System.  out . println (}      BMW523 {       BMW523 () {          System.  out . println (}      Customer {         main (string[] args) {          =  BMW320 ();           =  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 BMW {       BMW () {                }  }      BMW320  BMW {       BMW320 () {          System.  out . println (}    BMW523  bmw{       BMW523 () {          System.  out . println (    }  }  

Factory class:

 Public Factory {       BMW createbmw (type) {           (type) {                     :                BMW320 ();             :                BMW523 ();            :              ;          }           ;      }  }  

Customer class:

 Public Customer {         main (string[] args) {          =  Factory ();           = FACTORY.CREATEBMW ();           = FACTORY.CREATEBMW ();      }  }  

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 opening and shutting principle, but the factory part seems not ideal,because every new type of vehicle is added, it is necessary to add the corresponding creation business logic in the factory class (the CREATEBMW (int type) method requires a new case), which is obviously contrary to the opening and closing 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.
Five, factory method mode
The factory method pattern removes the static property of the factory method in the simple Factory mode, allowing it to inherit from 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.
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 specific factory role must implement or the parent class that must inherit. In Java it is implemented by an abstract class or interface.
2) Specific factory role: it contains code related 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.
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 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!

The code is as follows:

Product Category:

Abstract BMW {       BMW () {                }  }    BMW320  BMW {       BMW320 () {          System.  out . println (    }  }    BMW523  bmw{       BMW523 () {          System. out. println (}  

To create a factory class:

Interface }      FactoryBMW320  factorybmw{               BMW320 createbmw () {              BMW320 ();      }    }    FactoryBMW523  FACTORYBMW {             BMW523 createbmw () {              BMW523 ();      }  }  

Customer class:

 Public Customer {         main (string[] args) {          =  FactoryBMW320 ();           = FACTORYBMW320.CREATEBMW ();             =  FactoryBMW523 ();           = 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.

The above is simple Factory mode, factory method mode, abstract Factory mode here.

Example background: As customers become more demanding, BMW needs different configurations of air conditioning and engine accessories. So the factory started to produce air conditioners and engines to assemble cars. At this time the factory has two series of products: air conditioning and engine. The BMW 320 series is equipped with a model air conditioner and a model engine, the BMW 230 series is equipped with B model air conditioning and B model engine. Concept: Abstract Factory mode is an upgraded version of the factory method pattern that is used to create a set of related or interdependent objects. For example, the BMW 320 series uses air-conditioning model A and engine model A, while the BMW 230 series uses air-conditioning model B and engine Model B, then using the abstract Factory mode, in the production of accessories for the 320 series, there is no need to develop accessories model, it will automatically according to the model of the production of the corresponding accessory model A. For the introduction of Baidu Encyclopedia on the Abstract Factory model, combined with this example: when each abstract product has more than one specific sub-class (air conditioning models A and b two, the engine also has models A and b two), factory role how to know which sub-class is instantiated? For example, each abstract product role has two specific products (product air conditioning has two specific products air conditioning A and air conditioning B). The abstract factory model provides two specific factory roles (BMW 320 series factory and BMW 230 series factory), respectively, corresponding to these two specific product roles, each specific factory role is responsible for the instantiation of one product role. Each specific factory class is only responsible for creating an instance of a specific subclass of the abstract product.

Abstract Factory mode Code

Product Category:

// engine and model public   engine {      }      enginea  engine{         enginea () {            System.  out . println (}      Enginebextends engine{         Engineb () {            System.  out . println (    }    }          aircondition {      }      airconditiona  aircondition{         Airconditiona () {            System.  out . println (    }    }      airconditionb  aircondition{         airconditionb () {            System. out. println (}   

To create a factory class:

// Create a factory interface public   abstractfactory {               Engine createengine ();             Aircondition createaircondition ();   }            FactoryBMW320  abstractfactory{                         Engine createengine () {                enginea ();        }                 Aircondition createaircondition () {              Airconditiona ();        }    }        FactoryBMW523  abstractfactory {                      Engine createengine () {                engineb ();        }                 Aircondition createaircondition () {              airconditionb ();        }        }   

Customer:

 Public Customer {           main (string[] args) {                      =  FactoryBMW320 ();            Factorybmw320.createengine ();          Factorybmw320.createaircondition ();                                 =  FactoryBMW523 ();            Factorybmw320.createengine ();          Factorybmw320.createaircondition ();      }    }  

On the difference between the abstract factory model and the factory method model, it is not said, feel more than a few examples can understand, there are many references to the product family, hierarchical structure and other concepts, said it is more difficult to understand.

The origin of the abstract factory patternThe origin of an abstract factory pattern is referenced below:  The origin of the abstract factory pattern or the earliest application, which is used to create Windows constructs that belong to different operating systems. For example, the command button and text box (text) are all Windows constructs, in the UNIX operating system Windows environment and Windows Operating System window environment, these two constructs have different local implementation, their details are different. In each operating system, there is a building family consisting of a Windows build. Here is the product family of button and text. Each window component constructs its own hierarchical structure, which is given abstract function description by an abstract role, and the specific subclass gives the specific implementation under different operating systems. It can be found that in the above product class diagram, there are two product hierarchy structures, namely the button hierarchy and the text hierarchy. There are also two product families, namely the UNIX product family and the Windows product family. The UNIX product family consists of a Unix button and a UNIX text product, while the Windows product family consists of Windows button and the Windows text product. The requirements for the creation of a product object are met by the hierarchy of a project, which has two specific engineering roles, namely Unixfactory and Windowsfactory. The Unixfactory object is responsible for creating products in the Unix product family, while the Windowsfactory object is responsible for creating products in the Windows product family. This is the application of abstract Factory mode, the solution of abstract Factory mode, such as: Obviously, a system can only run in the windows of one operating system, but not on different operating systems at the same time. Therefore, the system can actually only consume products belonging to the same product family. In modern applications, the use of abstract Factory mode has been greatly expanded, no longer require the system to consume only one product family.    Summary: Whether it's a simple factory model, a factory approach 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.        therefore, when using the factory model, it is only necessary to care whether the purpose of reducing couplingto the

The Factory mode of Java design 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.