[Reprinted] simple factory Mode

Source: Internet
Author: User
Tags define abstract

Simple factory, factory method, and abstract factory. These three modes have similar names and are used to create objects, which is easy to confuse. I have reprinted two articles to illustrate these models and to make them clearer.Article.
From the perspective of the "Open and Close principle", the three modes have the following features:

    • Simple Factory: when adding new products, you need to modify the original factoryCodeThe logic for creating product objects is concentrated in factory roles.
    • Factory method: Suitable for adding products (you only need to add specific factory classes and product classes, without modifying the original Factory Code)
    • Abstract Factory: it is suitable for adding product families (existing factory classes do not need to be changed). However, this mode is not suitable for adding a product to a similar product family (the abstract factory class interface needs to be modified, the impact is global)

 

The reprinted content is as follows:

Part 1: simple factory Model

Http://blog.csdn.net/ai92/article/details/209198 (released on)

I. Introduction
A decade ago, he had three cars in his house, Benz, BMW, Audi, and hired a driver to drive for him. However, it is always strange for the nouveau riche to take a taxi: the Benz car was followed by the driver and said, "drive a taxi !", When he got on BMW, he said, "kaibao carriage !", Get on with Audi and say, "Drive on AUDI !". You must say: this person is ill! Just say you can't drive ?!
When we put the act of this nouveau riche into ourProgramThis is a common phenomenon during design. Fortunately, this disease can be avoided in OO (Object-Oriented) languages. The following introduces the topic of this article based on the Java language:Factory Model.
Ii. Classification
The factory mode mainly provides a transitional interface for creating objects, so that the specific process of creating objects is blocked and isolated to improve flexibility.

Factory models are classified into three types in Java and patterns:
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.

Both of them are acceptable. In this article, we use the classification method of Java and mode. Let's take a look at how these factory models "cure.

3. Simple factory Model

The simple factory mode is also called the static factory method mode. After renaming, we can see that this mode must be very simple. Its purpose is 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 judgment logic. In Java, it 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. It is implemented by interfaces or abstract classes in Java.

3) specific product role: the object created by the factory class is the instance of this role. It is implemented by a specific class in Java.

To use class diagrams to clearly express the relationships between them (if you are not familiar with class diagrams, refer to my article on class diagrams ):

How can we use the simple factory model? Let's transform the mode of transportation for the nouveau riche in a simple factory model-now the nouveau riche just needs to sit in the car and say "Drive" to the driver.

// Abstract Product role

Public interface car {

Public void drive ();
}

// Specific product role
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: P)
// Factory role

Public class driver {

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

// Judge the logic and 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 startup ......

Public class magnate {

Public static void main (string [] ARGs ){

Try {
// Tell the driver that I am taking the Mercedes today
Car car = driver. drivercar ("Benz ");
// Run the following command: Drive
Car. Drive ();

...

You can run the program after filling in the other information of the program. If you put all classes in one file, do not forget that only one class can be declared as public. This program runs in jdk1.4.

The relationships between classes in the program are described as follows:

This is a simple factory model. How is it easy to use? So what benefits does it bring?
First, after using the simple factory model, our program is not "abnormal" and is more in line with the actual situation. Besides, the client has no responsibility for directly creating product objects, instead, it is only responsible for "consuming" Products (just as the act of a nouveau riche ).

Next we will analyze the simple factory mode from the principle of opening and closing (open to expansion; and change and 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. So for the product part, it is in line with the principle of opening and closing; but the factory part does not seem ideal, because every time a car is added, the corresponding business logic or judgment logic must be added to the factory class, which is obviously against the open and closed principle. We can imagine that the factory category is passive when new products are added. For such a factory class (in our example it is a driver master), we call it an all-powerful class or a god class.
The example here is the simplest case, whileIn practical applications, the product is probably a multi-level tree structure.. Since there is only one factory class in the simple factory model to correspond to these products, this may make our God exhausted, but also tired of our programmers :(
So the factory method model emerged as the savior.

Iv. Factory method mode

The factory method mode removes the static attribute of the factory method in the simple factory mode so that it can be inherited by the quilt class. In this way, the pressure on the factory method in the simple factory mode can be shared by different factory subclass in the factory method mode.

You should roughly guess the structure of the factory method mode, and look at its 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 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.

2) specific factory role: it contains Code related to the specific business logic. An application is called to create the objects of a specific product.

3) Abstract Product role: it is the parent class or implemented interface inherited by a specific product. In Java, abstract classes or interfaces are generally used for implementation.

4) specific product role: the object created by the specific factory role is the instance of this role. It is implemented by specific classes in Java.

Use a class chart to clearly represent the relationship between them:

The factory method mode uses multiple sub-classes inherited from the abstract factory role to replace the "God class" in the simple factory mode ". As mentioned above, it shares the pressure on the object, and makes the structure more flexible-when new products (I .e. the car of the nouveau riche) are generated, as long as the product role is generated according to the contract provided by the abstract Product role and the abstract factory role, 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!

We still use the old rule to use a complete example to see how 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's master to remember and maintain any car. He will use it! 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:

// Abstract the product role. The specific product role is similar to the simple factory model, but it is more complicated.
// 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 ();
}
}

// Corresponding relationship with specific products...
// The attacker is welcome.
Public class magnate

{

Public static void main (string [] ARGs)

{

Try {
Driver driver = new benzdriver ();

Car car = driver. drivercar ();

Car. Drive ();

}

......

}

We can see that the addition of factory methods 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. If this problem cannot be avoided, consider combining the simple factory mode with the 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.

V. Summary

The factory method mode seems to have perfectly packaged the object creation, so that the client program only processes 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 specific object to use.

Does the simple factory mode and factory method mode actually avoid code changes? No. In the simple factory mode, the new product is added to modify the judgment statement in the factory role. In the factory method mode, the judgment logic is either left in the abstract factory role, either write down the specific factory role in the customer Program (as in the above example ). In addition, changes to product object creation conditions will inevitably lead to changes to the factory role.

In this situation,Java reflection mechanism and configuration fileThe clever combinationSpringIs perfectly reflected.

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. Let's illustrate it with an example.

Bmwcar and benzcar in the figure are two product trees (product hierarchy), while benzsportscar and bmwsportscar are one product family. They can all be placed in the sports car family, so their functions are related. Bmwbussinesscar and benzsportscar are also product families.
Return to the topic of the abstract factory model.

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.

Abstract Factory: 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 ):

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

2) specific factory role: it contains Code related to the specific business logic. An application is called to create the objects of a specific product. In Java, it is implemented by a specific class.

3) Abstract Product role: it is the parent class or implemented interface inherited by a specific product. In Java, abstract classes or interfaces are generally used for implementation.

4) specific product role: the object created by the specific factory role is the instance of this role. It is implemented by specific classes in Java.

The class diagram is as follows:

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. But be sure to meet the conditions for using the abstract factory model.

 

Part 2: An Example of an abstract factory

The following example of an abstract factory is transferred from another blog(Address: http://wuyuetian.iteye.com/blog/638401, 2010-2010-2010-2010-2010)

An example: due to business needs, our company introduced a machine drawing to easily draw different geometric shapes, such as circles, squares, and triangles. However, you may need to manually draw a graph. Each geometric graph must have two methods: Drawing draw () and removing erase (). Use the abstract factory to solve this problem.
Define abstract products first
Java code
Public interface shape {
Public void draw ();
Public void erase ();
}
Public interface circle extends shape {
}
Public interface square extends shape {
}
Public interface triangle extends shape {
}

Then define the specific products of the handwritten version:
Java code

Public class handcircle implements circle {
Public void draw (){
System. Out. println ("handcircle. Draw ()");
}
Public void erase (){
System. Out. println ("handcircle. Erase ()");
}
}
Public class handsquare implements square {
Public void draw (){
System. Out. println ("handsquare. Draw ()");
}
Public void erase (){
System. Out. println ("handsquare. Erase ()");
}
}
Public class handtriangle implements triangle {
Public void draw (){
System. Out. println ("handtriangle. Draw ()");
}
Public void erase (){
System. Out. println ("handtriangle. Erase ()");
}
}

Then define the specific products of machine manufacturing:
Java code
Public class machinecircle implements circle {
Public void draw (){
System. Out. println ("machinecircle. Draw ()");
}
Public void erase (){
System. Out. println ("machinecircle. Erase ()");
}
}
Public class machinesquare implements square {
Public void draw (){
System. Out. println ("mahchinesquare. Draw ()");
}
Public void erase (){
System. Out. println ("mahchinesquare. Erase ()");
}
}
Public class machinetriangle implements triangle {
Public void draw (){
System. Out. println ("machinetriangle. Draw ()");
}
Public void erase (){
System. Out. println ("machinetriangle. Erase ()");
}
}

Define the abstract factory, and the class implementing this interface will create three products of different levels.
Java code
Public interface arttracer {
Public circle createcircle ();
Public Square createsquare ();
Public triangle createtriangle ();
}

Specific Factory:
Java code
// The Factory of the handwritten version
Public class handtracer implements arttracer {
Public circle createcircle (){
Return new handcircle ();
}
Public Square createsquare (){
Return new handsquare ();
}
Public triangle createtriangle (){
Return new handtriangle ();
}
}

// Machine manufacturing factory
Public class machinetracer implements arttracer {
Public circle createcircle (){
Return new machinecircle ();
}
Public Square createsquare (){
Return new machinesquare ();
}
Public triangle createtriangle (){
Return new machinetriangle ();
}
}

Finally, write the client for testing:
Java code
Public class client {
Public static void main (string [] ARGs ){
Arttracer = new handtracer ();
Arttracer. createcircle (). Draw ();
Arttracer. createcircle (). Erase ();
Arttracer. createsquare (). Draw ();
Arttracer. createsquare (). Erase ();
Arttracer. createtriangle (). Draw ();
Arttracer. createtriangle (). Erase ();
System. Out. println ("--------------------------");
Arttracer = new machinetracer ();
Arttracer. createcircle (). Draw ();
Arttracer. createcircle (). Erase ();
Arttracer. createsquare (). Draw ();
Arttracer. createsquare (). Erase ();
Arttracer. createtriangle (). Draw ();
Arttracer. createtriangle (). Erase ();
}
}

 

Part 3 UML diagram of three modes

Simple Factory

Factory method

Abstract Method

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.