Design Mode (1) Factory mode Factory (creation type)

Source: Internet
Author: User
 
 

Design Mode 1 factory mode Factory

In object-oriented programming, the most common method is to generate an object instance with a new operator. The new operator is used to construct an object instance. However, in some cases, directly generating an object using the new operator may cause some problems. For example, the creation of many types of objects requires a series of steps: you may need to calculate or obtain the initial settings of the object; select which sub-object instance to generate; or, before generating the required objects, you must turn them into helper objects. In these cases, the establishment of a new object is a "process", not only an operation, like a gear drive in a large machine.

Mode Problems: How can you easily construct an object instance without worrying about the details and complex processes of constructing an object instance?

Solution: Create a factory to create objects.

Implementation:

I. 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 and then use it.
2) simple factory model: an industrial revolution emerged later. You do not need to create a BMW. Because the customer has a factory to help him create a BMW. What kind of car he wants, this factory can be built. For example, you want a 320i series car. The factory creates this series of vehicles. That is, the factory can create products.
3) in the era of factory method model: to satisfy customers, more and more BMW series, such as 320i, 523i, and 30li series, cannot be created in one factory. As a result, multiple detailed factories are separated separately. Each detailed factory creates a series. That is, the detailed factory class can only create a detailed product. However, the BMW factory is still abstract. You need to specify a detailed factory to produce a car.
4) Abstract Factory model era: With the increasing requirements of customers, BMW cars must be equipped with air conditioners. In addition, the air conditioner must be used by series vehicles. The factory began to produce BMW cars and air conditioners.
Finally, the customer only wanted to say to the salesman of BMW: I want a 523i air-conditioned car, And the salesman gave him a 523i air-conditioned car directly. Instead of creating a 523i air-conditioner carriage.
(Let me just give you an example. When it comes to BMW's configuration of air conditioners, it is totally for example, or even a bit of a drag. Which car or air conditioner must be used accordingly)
This is the factory model.
Ii. Classification 
The factory mode mainly provides a transitional interface for object creation, so as to shield and isolate the detailed process of object creation to improve flexibility.
The factory model can be divided into three types:
1) simple factory)
2) Factory method)
3) Abstract Factory mode (Abstract Factory)
These three models are gradually abstracted from top to bottom and more general.
In design patterns, gof classifies factory patterns into two types: factory methods and abstract factory ). The simple factory mode is a special case of the factory method mode.
Iii. Differences
Factory method mode:
An abstract product class that can derive multiple detailed product classes.
An abstract factory class can derive multiple detailed factory classes.
Each detailed factory class can only create a detailed product class instance.
Abstract Factory mode:
Multiple abstract product classes. Each abstract product class can derive multiple detailed product classes.
An abstract factory class can derive multiple detailed factory classes.
Each detailed factory class can create multiple detailed product class instances.
Differences:
The factory method mode only has one abstract product class, while the abstract factory mode has multiple.
The factory method mode's detailed factory class can only create an instance of the detailed product class, while the abstract factory mode can create multiple.
Both.


Iv. Simple factory Model
Create a factory (a function or a class method) to create a new object.
Distribution Description Introduction: from scratch. The customer creates his own BMW and then uses it for use.
 


<? PHP/*** car series **/class bwm320 {function _ construct ($ Pa) {}} class bmw523 {function _ construc ($ Pb) {}}/***** the customer created his own BMW */Class Customer {function createbmw320 () {return New bwm320 ();} function createbmw523 () {return New bmw523 ();}}


The customer needs to know how to create a car, and the customer and the car are closely coupled. In order to reduce CouplingThe factory class appeared, and the operation details of creating a BMW were put into the factory. The customer directly used the factory creation method to import the desired BMW model, you do not have to know the details of the Creation. this is the Industrial Revolution:Simple factory Mode

That is, we create a factory method to create new objects.



Product Type:

<? PHP/*** car series **/abstract class BWM {function _ construct ($ Pa) {}} class bwm320 extends BWM {function _ construct ($ PA) {}} class bmw523 extends BWM {function _ construc ($ Pb ){}}

Factory type:

/***** Create a car at the factory */class factory {static function createbmw ($ type) {Switch ($ type) {Case 320: return New bwm320 (); Case 523: return new bmw523 ();//....}}

Customer type:

/***** The customer obtains the car through the factory */Class Customer {private $ BMW; function getbmw ($ type) {$ this? -> BMW = Factory: createbmw ($ type );}}


The simple factory mode is also called the static factory method mode. You can see that this mode is very easy to rename. It has a very easy purpose: to define an interface for creating objects.
Let's take a look at its composition:
1) Factory roles: this is the core of this model and contains some commercial logic and inference logic.
2) Abstract Product role: it is generally the parent class or implemented interface inherited by the product in detail.
3) detailed product role: the object created by the factory class is the instance of this role. It is implemented by a detailed class in Java.

Below we will analyze the simple factory mode from the principle of opening and closing (open to expansion; closed to change. When the customer no longer meets the existing model of a new type of car, the customer wants a new type of car with fast speed, and only wants the car to conform to the contract of the abstract product, so we only need to notify the factory class that it can be used by the customer. So for the product part, it is in line with the principle of opening and closing; but the factory part does not seem ideal,Each time a new type of vehicle is added, a corresponding case must be added to the createbmw ($ type) method in the factory class. This obviously violates the principle of opening and closing.. We can imagine that the factory category is very passive when new products are added. For this factory class, we call it omnipotent or God class.
The example is the simplest case. In practical applications, it is very likely that the product is a multi-level tree structure. Because there is only one factory type in the simple factory model to correspond to these products, this may make our God very tired, and we are tired of these procedures :(
So the factory method model emerged as the savior. The factory class is defined as an interface, and the implementation of the corresponding factory class is added for each newly added vehicle type, so that the factory design can be expanded, instead of modifying the original code.
V. Factory method mode
The factory method mode removes the static attribute of the factory method in the simple factory mode so that it can inherit from the quilt class. In this way, the pressure on the factory method concentrated in the simple factory mode can be shared by different factory subclass in the factory method mode.
Factory method mode composition:
1) Abstract Factory role: this is the core of the factory method model and has nothing to do with the application. It is an interface that the factory role must implement or a parent class that must be inherited. In Java, it is implemented by abstract classes or interfaces.
2) Detailed factory role: it contains code related to detailed business logic. The application calls the API to create detailed product objects.
3) Abstract Product role: it is the parent class or implemented interface inherited by the product in detail. In Java, abstract classes or interfaces are generally used for implementation.
4) detailed product role: the object created by the detailed factory role is the instance of this role. It is implemented by detailed classes in Java.
The factory method mode replaces the "God class" in the simple factory mode with multiple subclasses inherited from the abstract factory role ". As mentioned above, the pressure on objects is shared, and the structure becomes flexible-when new products are generated, it is generated only according to the contract provided by the abstract Product role and the abstract factory role, so it can be used by the customer without having to modify any existing code. We can see that the structure of the factory role is also in line with the principle of opening and closing!
 


The Code is as follows:

Product Type:

<? PHP/*** car series **/abstract class BWM {function _ construct ($ Pa) {}} class bwm320 extends BWM {function _ construct ($ PA) {}} class bmw523 extends BWM {function _ construc ($ Pb ){}}


Create a factory:

/*** Create a factory interface **/interface factorybmw {function createbmw ();} /***** create a bwm320 car */class factorybwm320 implements factorybmw {function createbmw ($ type) {return New bwm320 ();}} /***** create a bwm523 car */class factorybwm523 implements factorybmw {function createbmw ($ type) {return New bmw523 ();}}


Customer type:

/*** The customer gets the car */Class Customer {private $ BMW; function getbmw ($ type) {Switch ($ type) {Case 320: $ bwm320 = new factorybwm320 (); return $ bwm320-> createbmw (); Case 523: $ bwm523 = new factorybwm523 (); return $ bwm320-> createbmw (); //....}}}


We can see that the increase in the factory method doubles the number of objects. When there are many product categories, there will be a large number of corresponding factory objects, which is not what we want. Since we cannot avoid this situation, we can consider combining the simple factory mode with the factory method mode to reduce the factory class: that is, for similar types on the product tree (usually brothers in the leaves of the tree), a simple factory model is used for implementation.

Factory method summary:
The factory method mode seems to have perfectly packaged the object creation, so that the client program can only process the interfaces provided by the abstract Product role. So do we have to spread code across factories? Not required. You may consider using the factory method mode in the following situations:
1) when the customer program does not need to know the creation process of the object to be used.
2) The objects used by the customer program may change, or they do not know which detailed object to use.


Does the simple factory mode and factory method mode actually avoid code changes? No. In the simple factory model, the addition of a new product changes the inference statement in the factory role. In the factory method model, the judgment logic is either left in the abstract factory role, either write down the detailed factory role in the customer Program (as in the preceding example ). In addition, changes to product object creation conditions will inevitably lead to changes to the factory role.
In the face of such a situation, we can use the reflection mechanism:

Class Customer {private $ BMW; function getbmw ($ type) {$ class = new reflectionclass ('factorybwm '. $ type); // create the reflection class of the 'factorybwm 'class $ instance = $ class-> newinstanceargs (); // It is equivalent to instantiating 'factorybwm '. $ type class return $ instance-> createbmw (); // or directly/*** $ instance = new 'factorybwm '. $ type (); * return $ instance-> createbmw ();*/}}

 

Vi. Abstract Factory Model
As the customer's requirements increase, BMW cars need to be equipped with air conditioners. As a result, this factory began to produce BMW cars and air conditioners required for configuration. At this time, the factory has two series of products: BMW cars and air conditioners. BMW must use the appropriate air conditioners for use. at this time, the use of a car factory and an air-conditioning factory can not meet our needs, we must confirm the relationship between the car and the air-conditioning. Therefore, the vehicle factory is associated with the air-conditioning factory. Therefore, the abstract factory model emerged.
It can be said that the difference between the abstract factory mode and the factory method mode lies in the complexity of object creation. In addition, the abstract factory model is the most abstract and general among the three.
The abstract factory mode provides an interface for the client to create product objects in multiple product families. The Abstract Factory mode must meet the following conditions:
1) there are multiple product families in the system, and the system may only consume one product at a time.
2) products belonging to the same product family are used by them.
Abstract The roles of the factory model (same as the factory method ):
1) Abstract Factory role: this is the core of the factory method model and has nothing to do with the application. It is an interface that the factory role must implement or a parent class that must be inherited. In Java, it is implemented by abstract classes or interfaces.
2) Detailed factory role: it contains code related to detailed business logic. The application calls the API to create detailed product objects.
3) Abstract Product role: it is the parent class or implemented interface inherited by the product in detail.
4) detailed product role: the object created by the detailed factory role is the instance of this role.

 

Its structure:


 
Example:
 

Code:

Product Type:

<? PHP/*** car series and model **/abstract class BWM {} class bwm523 extends BWM {} class bwm320 extends BWM {}/*** air conditioner **/abstract class aircondition {} class airconditionbwm320 extends aircondition {} class airconditionbwm52 extends aircondition {}
Create a factory:

/*** Create a factory interface **/interface factorybmw {function createbmw (); function createairc ();} /***** create a bwm320 car */class factorybwm320 implements factorybmw {function createbmw () {return New bwm320 ();} function createairc () {// air conditioner return New airconditionbwm320 () ;}/ *** create a bwm523 car */class factorybwm523 implements factorybmw {function createbmw () {return New bwm523 ();} function createairc () {return New airconditionbwm523 ();}}
Customer:

/*** The customer gets the car */Class Customer {private $ BMW; private $ AIRC; function getbmw ($ type) {$ class = new reflectionclass ('factorybwm '. $ type); // create the reflection class of the person class $ instance = $ class-> newinstanceargs (); // It is equivalent to instantiating the person class $ this-> BMW = $ instance-> createbmw (); $ this-> AIRC = $ instance-> createairc ();}}


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.