Design mode-Factory mode

Source: Internet
Author: User

1. first of all, the three main characteristics of object-oriented: encapsulation, inheritance, polymorphism, two basic principles: Single duty principle and open closure principle. These are the most basic, if you feel unfamiliar, please Baidu, do not repeat.

2. The factory model is divided into three types:1) Simple Factory mode,2) factory method mode,3) abstract Factory mode. These three modes are progressively abstracted from top to bottom and more general.

3. application of the factory model:

1) cannot foresee what kind of instance to create when coding

2) The system should not rely on the details of how product class instances are created, combined, and expressed.

4. Simple factory: Consists of three roles, 1) The factory class role, which is the core of this model, there are certain business logic and judgment logic. It is often implemented by a specific class. 2) abstract product roles, which are generally either parent classes with product inheritance or interfaces implemented. Typically implemented by interfaces or abstract classes. 3) specific product roles, the object created by the factory class is an instance of this role, typically implemented by a class.

Its logical relationship is as follows:

650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M02/54/77/wKiom1SDJDWhg8Y5AADm0R9G-Oc586.jpg "title=" 6oxie[ $X ' @a{am~$~ygcoi5.jpg ' alt= "wkiom1sdjdwhg8y5aadm0r9g-oc586.jpg"/>

Case:Ten years ago, there was an outbreak, his family had three cars (Benz(Mercedes-Benz),BMW(BMW),Audi(Audi) It seems that the person is more patriotic, no Japanese car, and hired a driver to drive for him. However, the outbreak of the car is always the case: onBenzafter the car, tell the driver."Drive the Mercedes! ", sit onBMWafter he said"Drive a BMW! ", sit onAudiafter he said"Open the Audi car! ". You must say: this man is sick! Why don't you just say drive?! and when we put this outbreak in the language of our program, we foundClanguage has always been in this way to ride! Fortunately, this kind of sick phenomenon isOOcan be avoided in the language.

after using the simple factory model, now the upstart just need to sit in the car and say to the driver: " Drive " you can do it. To see how this is achieved:

// Abstract Product Roles

Public Interface car{

Public void Drive ();

}

// Specific Product Roles

Public class Benz implements car{

Public void Drive () {

System. out . println ("Driving Benz");

}

}

Public class BMW implements car{

Public void Drive () {

System. out . println ("Driving Bmw");

}

}

。。。 (Audi I will not write: P)

// Factory class Roles

Public class driver{

// Factory Method

// Note The return type is abstract product role

Public Static Car Drivercar (String s) throws Exception {

// judgment logic, return the specific product role to the client

if (S.equalsignorecase ("Benz")) return New Benz ();

Else if (S.equalsignorecase ("BMW"))

return New BMW ();

......

Else Throw New Exception ();

。。。

// welcome to the upstart ...

Public class magnate{

Public Static void Main (string[] args) {

Try {

// tell the driver I'm riding today .

Car car = driver.drivercar ("Benz");

// Next command: drive

Car.drive ();

。。。

If you put all the classes in a file, the last most Driver This class is declared public. This is the simple factory model with the following benefits:

1) after using the simple factory model, the client is exempt from the responsibility of creating the product directly, and is only responsible for "consuming" the product (as the upstart does).

2) from the angle of the open and close principle, when the nouveau riche added a car, as long as the abstract products in accordance with the contract, then as long as the notification factory class, you can be used by customers. For the product, it is in line with the principle of open and closed, but for the factory is not ideal, because each additional vehicle, in the factory class to add business logic and judgment logic, which is clearly against the opening and closing principle.

3) for such a factory class (the driver in the example), we call it the Almighty or the God class.

5. Recommendation: 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 break our God class and then spoil our lovely programmer .
As I mentioned earlier the simple factory model applies to the case where the business will be simple. The complex business environment may not be very adaptable. This should be done by the factory method mode!!

6. Factory mode: composition,1) Abstract Factory role: This is the core of the factory method pattern, and it is not application-agnostic. is the interface that the specific factory role must implement or the parent class that must inherit. Generally implemented by an abstract class or interface. 2) specific factory roles, which also have code related to specific business logic. An object called by an application to create a corresponding specific product, typically implemented by a specific class. 3) abstract product role, which is the parent class of the specific product inheritance or the implementation of the interface. Generally implemented by an abstract class or interface. 4) Specific product roles: the object created by the specific factory is an instance of this role. Typically implemented by a specific class.

From the above, the factory model is a simple model based on the new volume of the factory abstraction.

7. Case Study: The bigger the upstart business, the more their own car. This can be bitter the driver master, what car it must remember, maintenance, all must go through him to use! So the nouveau riche sympathy he said: "Look at you and me for so many years, you do not have to work so hard, I assign you a few staff, you just keep them in mind!" As a result, the management of the factory method pattern arose. The code is as follows:

Abstract product roles, specific product roles similar to the simple factory model, just become more complex, here slightly. Abstract Factory role public interface Driver{public Car Drivercar ();} public class Benzdriver implements Driver{public Car Drivercar () {return new Benz ();}} public class Bmwdriver implements Driver{public Car Drivercar () {return new BMW ();}} ...//should correspond with specific products, here slightly ...//Please Mr. Upstart public class Magnate{public static void Main (string[] args) {Try{driver Driver = New Benzdriver (); Car car = Driver.drivercar (); car.drive ();} catch (Exception e) {}}}

8. The factory method uses an abstract factory role as the core instead of using a specific class as the core in a simple factory pattern. the advantages of the factory model are: Using the open and closed principle to analyze the plant method model. When a new product (ie, the upstart car) is produced, it can be used by the customer instead of modifying any existing code as long as it is generated according to the contract provided by the abstract product role and the abstract factory role. It seems that the factory method mode is completely in line with the open and closed principle!

9. Recommendation: Using the factory approach model is sufficient to meet most of the business requirements that we may encounter. But when the product variety is very long, there will be a lot of corresponding factory class, this should not be what we want. So I suggest that in this case, the simple factory model combined with the factory method pattern should be used to reduce the factory class: The Simple factory pattern is used for similar species on the product tree (which is usually brothers in the leaves of the tree).
Of course, special treatment is special: There are different product trees in the system, and there are product families on the product tree, then the abstract Factory mode may be used in this case.

10. Summary: Let's take a look at the simple factory model, the factory method model to enlighten us:
If we do not use Factory mode to implement our example, perhaps the code will be much less-just to implement the existing car, do not use polymorphism. But on maintainability, scalability is very poor (you can imagine adding a car to affect the class). So in order to improve scalability and maintainability, it is worthwhile to write more code.

11. Abstract Factory mode: A family of products composed of product families, which are located in different product hierarchy structures and feature associated products. For example, Bmwcar and benzcar are two product trees (product hierarchies). and Benzsportscar and bmwsportscar are a product family. They can all be put into the sports car family, so the function is connected. Similarly Bmwbussinesscar and Benzsportscar are also a product family.

back to the topic of the abstract product model, so to speak, it differs from the factory method pattern in the complexity of the object that needs 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 an interface to the client to create product objects in multiple product families. And the following conditions are also used in the Abstract Factory mode:
1There are multiple product families in the system, and the system may only consume one product at a time
2) when used with products belonging to the same product family.
take a look at the various roles of the abstract Factory model (as in the factory approach):
Abstract Factory Role: This is the core of the factory method pattern, and it is not application-agnostic. is the interface that the specific factory role must implement or the parent class that must inherit. It is implemented by an abstract class or interface.
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. It is implemented by specific classes.
Abstract Product Role: It is the parent of a specific product inheritance or an interface implemented. In theJavain general there are abstract classes or interfaces to implement.
Specific product roles: the object created by the specific factory role is an instance of this role. In theJavaare implemented by specific classes.

I have seen the first two patterns, the coordination between the various roles of this pattern should have a number of hearts, I will not cite specific examples. Just be sure to meet the criteria for using the abstract Factory mode Oh, or even if there are multiple product trees, there are product families, but not used.

Reference article: http://www.cnblogs.com/poissonnotes/archive/2010/12/01/1893871.html

This article is from "Tiger Brother's Blog" blog, please be sure to keep this source http://7613577.blog.51cto.com/7603577/1587209

Design mode-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.