Factory method pattern of java design pattern (Factory Method Pattern)

concept

The Factory Method Pattern (Factory Method Pattern) is also known as the Factory Pattern, also known as the Virtual Constructor (Virtual Constructor) pattern or the Polymorphic Factory (Polymorphic Factory) pattern, which belongs to the class creation pattern.

The factory method pattern is an object-oriented design pattern that implements the "factory" concept. Like other creational patterns, it also deals with creating objects without specifying their concrete type.

The essence of the factory method pattern is "to define an interface for creating objects, but let the class that implements this interface decide which class to instantiate. The factory method defers the instantiation of the class to the subclass."

use

Although the factory method pattern and [simple factory pattern][2] both use factories to create objects, the biggest difference between them is that the factory method pattern is designed to fully comply with "[opening and closing principles][3]".

The factory method pattern can be used when:

A class does not know the class of the object it needs: In the factory method pattern, the client does not need to know the class name of the specific product class, but only needs to know the corresponding factory, and the specific product object is created by the specific factory class; The client needs to know the factory class for creating concrete products.

A class specifies which object to create through its subclass: In the factory method pattern, the abstract factory class only needs to provide an interface for creating products, and its subclass determines the specific object to be created, using object-oriented polymorphism And [Liskov Substitution Principle] [3], when the program is running, the subclass object will cover the parent class object, which makes the system easier to expand.

Delegate the task of creating objects to one of the multiple factory subclasses. When using it, the client does not need to care which factory subclass creates the product subclass. It can be dynamically specified when necessary. The class name of the specific factory class can be assigned Stored in configuration file or database.

Method to realize

The factory method pattern includes the following roles:

Product: abstract product ( Operation)

ConcreteProduct: concrete product ( OperationAdd)

Factory: abstract factory ( IFactory)

ConcreteFactory: concrete factory ( AddFactory)

[QQ20160412-0][4]

Here is also an example with a calculator. In the case of keeping several methods of Operation, OperationAdd, OperationDiv, OperationSub, OperationMuletc. unchanged, modify the factory class ( ) in the simple factory pattern OperationFactory. Instead of the original "universal" big factory class, here is a factory method instead:

//工厂接口
public interface IFactory {
    Operation CreateOption();
}

//加法类工厂
public class AddFactory implements IFactory {

    public Operation CreateOption() {
        return new OperationAdd();
    }
}

//除法类工厂
public class DivFactory implements IFactory {

    public Operation CreateOption() {
        return new OperationDiv();
    }
}

//除法类工厂
public class MulFactory implements IFactory {

    public Operation CreateOption() {
        return new OperationMul();
    }
}

//减法类工厂
public class SubFactory implements IFactory {

    public Operation CreateOption() {
        return new OperationSub();
    }
}

In this way, when you want to perform an addition operation in the client, you need the following method:

public class Main {

    public static void main(String[] args) {
        IFactory factory = new AddFactory();
        Operation operationAdd =  factory.CreateOption();
        operationAdd.setValue1(10);
        operationAdd.setValue2(5);
        System.out.println(operationAdd.getResult());
    }
}

At this point, a factory method pattern has been written.


From the perspective of code size, this factory method pattern is more complicated than the simple factory method pattern. There are corresponding factories for different operation classes. Many people have the following questions:

It seems that the factory method pattern is more complicated than the simple factory pattern?

Is the factory method pattern no different than creating objects myself? Why do we need to build more factories?

Let's take a deep look at the factory method pattern for the above two questions.

Pros and Cons of the Factory Method Pattern

Why use factories to create objects?

Encapsulate object creation process

In the factory method pattern, the factory method is used to create the products required by the customer, and at the same time hides the details of which specific product class will be instantiated from the customer. The user only needs to care about the factory corresponding to the required product, and does not need to care about creating details without even knowing the class name of the specific product class.

The polymorphic design based on factory roles and product roles is the key to the factory method pattern. **It enables the factory to independently determine what product object to create, and the details of how to create this object are completely encapsulated within the specific factory. **The reason why the factory method pattern is also known as the polymorphic factory pattern is because all concrete factory classes have the same abstract parent class.

Why does each object have a separate factory?

Comply with "[Open-Closed Principle][5]"

The main purpose is for decoupling. When adding a new product to the system, there is no need to modify the interface provided by the abstract factory and the abstract product, no need to modify the client, and no need to modify other specific factories and specific products, but only need to add a specific factory and specific product. In this way, the scalability of the system becomes very good, which fully complies with "[opening and closing principle][3]".

The above are the advantages of the factory method pattern. However, the factory pattern also has some unsatisfactory places:

When adding a new product, it is necessary to write a new specific product class and provide a corresponding specific factory class. The number of classes in the system will increase in pairs, which increases the complexity of the system to a certain extent. There are more The class needs to be compiled and run, which will bring some additional overhead to the system.

Considering the scalability of the system, it is necessary to introduce an abstraction layer, which is defined in the client code using the abstraction layer, which increases the abstraction and difficulty of understanding of the system, and may require the use of DOM, reflection and other technologies during implementation. Increased the difficulty of system implementation.

Difference between factory method and simple factory

The factory pattern overcomes the shortcoming that the simple factory pattern violates the [open-closed principle][3], and maintains the advantages of encapsulating the object creation process.

They all encapsulate the creation of objects centrally, so that when an object needs to be replaced, it can be realized without major changes, reducing the coupling between the client and the product object.

Summarize

The factory method pattern is a further abstraction and promotion of the simple factory pattern.

Due to the use of object-oriented polymorphism, the factory method pattern maintains the advantages of the simple factory pattern and overcomes its shortcomings.

In the factory method pattern, the core factory class is no longer responsible for the creation of all products, but the specific creation work is handed over to subclasses. This core class is only responsible for giving the interface that the specific factory must implement, not responsible for the details of the product class being instantiated, which makes the factory method pattern allow the system to introduce new products without modifying the role of the factory.

The main advantage of the factory method pattern is that there is no need to modify the existing system when adding new product categories, and it encapsulates the creation details of product objects. The system has good flexibility and scalability; its disadvantage is that it needs to add new products while adding new products. The factory, resulting in the number of system classes increased in pairs, to a certain extent increased the complexity of the system.

Guess you like

Origin blog.csdn.net/zy_dreamer/article/details/132364309