Factory mode and abstract factory Mode

Source: Internet
Author: User
Factory mode and abstract factory Mode

I. Introduction
Ten years ago, there was a bad user who had three cars in his house (Benz(Mercedes-Benz ),BMW(BMW ),Audi(Audi) it seems that this man is more patriotic and has no Japanese car.) He also hired a driver to drive for him. However, when a taxi is used by a burst user, it always goes like this:BenzFollowed by the driver"Drive a Mercedes-Benz!", Sit onBMWThen he said"Kaibao carriage!", Sit onAudiThen he said"Drive Audi!". You must say: this person is ill! Just say you can't drive ?! When we put this explosive behavior into ourProgramLanguage, we found thatCThe language is always used in this way! Fortunately, this symptom isOoLanguage can be avoided. The following usesJavaLanguage-based introduction to the topic of this article: factory model !!

II. Introduction
The factory mode provides interfaces for object creation. The factory model follows 《JavaThere are three types of expressions in the model:
1.Simple factory Mode(Simple factory)
2.Factory method mode(Factory method)
3.Abstract Factory Model(Abstract Factory)
These three models are gradually abstracted from top to bottom and more general. Another kind of classification is to look at the simple factory model as a special case of the factory method model. The two are classified as one type. The following two scenarios use the factory model:
1.You cannot predict the type of instance to be created during encoding.
2.The system should not rely on the details of how product instances are created, combined, and expressed.

3. Simple factory Model
As the name suggests, this mode is simple and easy to use when the business is relatively simple.
It consists of three roles (for the relationship, see the class diagram below ):
1. Factory roles: this is the core of this model and contains some commercial logic and judgment logic. InJavaIt is often implemented by a specific class. 2. Abstract Product role: it is generally the parent class or implemented interface inherited by a specific product. InJavaIs implemented by interfaces or abstract classes. 3. Specific product role: the object created by the factory class is the instance of this role. InJavaIs implemented by a specific class.

How can we use the simple factory model? Let me give you an example. I think this is much easier to understand than a large theoretical text description! Let's take care of the nouveau riche.: P
After using the simple factory model, the new user just needs to sit in the car and say to the driver:"Driving"You can. Let's see how it is implemented:
//Abstract Product role
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 ");
}
}
... (I will not write about Audi. )

//Factory role
Public class driver {

//Factory method
//Note that the return type is abstract Product role.
Public static car drivercar (string s) throws exception {

//The judgment logic returns the specific product roleClient
If (S. equalsignorecase ("Benz") return New Benz ();
Else if (S. equalsignorecase ("BMW "))
Return new BMW ();

......
Else throw new exception ();
...

// Welcome to the startup......
Public class magnate {
Public static void main (string [] ARGs ){
Try {
//Tell the driver that I'm in a Mercedes-Benz today
Car car = driver. drivercar ("Benz ");
//Run the following command: Drive
Car. Drive ();
...
If you put all classes in one file, do not forget that only one class can be declaredPublic. The relationships between classes in the program are as follows:

This is the simple factory mode. The following are the benefits: first, after using the simple factory mode, our program is not " " , in addition, the client is not responsible for directly creating product objects, but only for " consume " products (such as by a nouveau riche ).
the simple factory mode is analyzed based on the principle of opening/closing. When a nouveau riche adds a car, as long as it complies with the contract of the abstract product, it can be used by the customer as long as the factory class is notified. For the product, it complies with the open and closed principles. -- is open to extensions and closed to modifications; however, it seems that the factory is not ideal, because every time a car is added, the corresponding business logic and judgment logic must be added to the factory class, which naturally violates the principle of opening and closing.
for such a factory class (in our example, it is a driver master ), we call it omnipotent or God.
in this example, it is likely that the product is a multi-level tree structure. Since there is only one factory class in the simple factory model to correspond to these products, this may break down our God class, and then get tired of our lovely programmer
As I mentioned earlier, the simple factory model is applicable when the business will be simple. However, it may not be suitable for complicated business environments. This should be done in the factory method mode !!

Iv. Factory method mode
Let's take a look at its composition:
1. Abstract Factory role: this is the core of the factory method model and has nothing to do with applications. It is an interface that must be implemented by a specific factory role or a parent class that must be inherited. InJavaIt is implemented by abstract classes or interfaces.
2. Specific factory role: it containsCode. An application is called to create the objects of a specific product. InJavaIt is implemented by a specific class.
3. Abstract Product role: it is the parent class or implemented interface inherited by a specific product. InJavaIs generally implemented using abstract classes or interfaces.
4. Specific product role: the object created by the specific factory role is the instance of this role. InJavaIs implemented by specific classes.
To use a class chart to clearly express the relationship between them:


we still use a complete example to see how the roles in the factory model are coordinated. In other words, the larger the startup business, the more cars they love. It's hard for the driver, master. Remember all the cars and maintenance should be used by him! As a result, the nouveau riche sympathized with him and said, "You don't have to work so hard in the future. I will assign you several people. You just need to manage them! As a result, the management of the factory method model emerged. The Code is as follows:
// abstracts the product role. The specific product role is similar to the simple factory model, it's just a little more complicated.
// Abstract Factory role
Public interface driver {
Public Car drivercar ();
}< br> public class benzdriver implements driver {
Public Car drivercar () {
return New Benz ();
}< BR >}< br> public class bmwdriver implements driver {
Public Car drivercar () {
return new BMW ();
}< BR >}< br> ...... // corresponds to a specific product. ...
// if you have any, please contact the user.
public class magnate
{< br> Public static void main (string [] ARGs)
{< br> try {
driver = new benzdriver ();

Car car = driver. drivercar ();
Car. drive ();
}catch (exception E)
{}< BR >}< br> factory methods use an abstract factory role as the core instead of using a specific class as the core in a simple factory model. Let's take a look at what the factory method model has brought to us? Use the open/closed principle to analyze the factory method mode. When a new product (that is, a nouveau riche car) is generated, it can be used by the customer as long as it is generated according to the contract provided by the abstract Product role and the abstract factory role, instead of modifying any existing code generation. It seems that the factory method mode is completely in line with the principle of opening and closing!
the factory method is sufficient to meet most of our business needs. However, when there are many product categories, there will be a large number of corresponding factory categories, which is not what we want. In this case, we recommend that you use the simple factory mode and factory method mode to reduce the factory class: that is to say, a simple factory model is used for similar types on the product tree (generally the leaves of the tree are sibling ones.
in special cases, you must take special measures: for different product trees in the system, in addition, product families exist on the product tree. In this case, the abstract factory model may be used.

V. Summary
Let's take a look at the inspiration given by the simple factory model and factory method model:
If we do not use the factory mode to implement our example, the code may be much reduced.--You only need to implement the existing cars without using polymorphism. But in terms of maintainability, scalability is very poor (you can imagine the class to be affected after adding a car ). Therefore, it is worthwhile to write more code to improve scalability and maintainability.

Vi. Abstract Factory Model
First, let's take a look at what is a product family: A family of products with different product levels and functions. If you read this sentence, you can understand this concept clearly. I have to admire you. Let's illustrate it with an example.

In the figure Bmwcar And Benzcar There are two product trees (product hierarchy ). Benzsportscar And Bmwsportscar Is a product family. They can all be placed in the sports car family, so their functions are related. LikewiseBmwbussinesscar And Benzsportscar It is also a product family.
Back to the topic of the abstract product model, we can say that the difference between it 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. Abstract Factory mode provides an interface for the client to create product objects in multiple product families. In addition, the abstract factory model must meet the following conditions:
1. The system has multiple product families, and the system can only consume one of them at a time.
2. Products belonging to the same product family are used by them.
Let's take a look at the roles of the abstract factory model (similar to the factory method ):
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 must be implemented by a specific factory role or a parent class that must be inherited. In Java It is implemented by abstract classes or interfaces.
Specific factory role: it contains code related to specific business logic. An application is called to create the objects of a specific product. InJava It is implemented by a specific class.
Abstract Product role: it is the parent class or implemented interface inherited by a specific product. In Java Is generally implemented using abstract classes or interfaces.
Specific product role: the object created by the specific factory role is the instance of this role. In Java Is implemented by specific classes.

 

After reading the first two models, I should be aware of the number of roles in this model. I will not give a specific example. You must pay attention to meeting the conditions for using the abstract factory model. Otherwise, even if there are multiple product trees, there are product families, but they cannot be used.

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.