Do you think the factory pattern is very simple, probably because you know just the tip of the iceberg

Many people think the factory pattern is very simple, but there is a build factories, to help us to construct objects only. So please try to answer the following questions below:

1, factory mode is divided into several categories?
2, GOF 23 kinds of design patterns, the factory method pattern and abstract factory pattern What is the difference?
3, not what GOF simple factory pattern 23 design patterns is?
4, a simple factory pattern, factory method pattern and abstract factory pattern to solve their problem? what is the difference?

If the above four questions, you can be a good answer, then this article is no need to continue to read on, otherwise, I suggest you learn the next article.

Three kinds of factory pattern {# toc_0}

Factory mode can be divided into three categories:

  • 1) Simple factory pattern (Simple Factory)

  • 2) factory method model (Factory Method)

  • 3) Abstract Factory (Abstract Factory)

These three models from top to bottom and gradually abstract and more general.

In GOF "Design Patterns" book factory mode will be divided into two categories: factory method model (Factory Method) abstract factory pattern (Abstract Factory).

The simple factory pattern (Simple Factory) is a factory method to see a special case of mode, both classified as a class.

The three factory pattern classification in the design mode are all created schema .

Create schema (Creational Pattern) instantiation process of the abstract class, can be created using separate software modules and objects in the object. In order to make more clear structure of the software, the outside world for these objects only need to know their common interface, but do not know the specific implementation details, the design of the entire system more in line with the principle of single responsibility.

Create schema is created in terms of what (What), who created (Who), when to create (When) and so provides the greatest possible flexibility for software designers.

Creating the schema hides the details of creating class instances, and how they are combined together to create the whole system to achieve the object is achieved by independent hidden objects.

Factory pattern is to create a schema more important. The main function of the factory model is to help us to instantiate an object. The reason why the plant model name contains words, because the instantiation object is achieved by a plant, the plant is replaced with a new operation.

The advantage of this package is an example of the details of the object, in particular the case for example of more complex life cycle or target should be centrally managed. It will bring greater scalability and minimize the amount of modification of your system.

Next we were introduced to the three factory pattern.

Simple factory pattern {# toc_1}

Simple factory pattern to create a schema belongs, also known as static factory method (Static Factory Method) mode. Simple factory pattern is determined by a factory object to create an instance of what kind of product class. Simple factory pattern is the factory model family is the most simple and practical model can be understood as a special mode of realization of different plants.

Before introducing simple factory pattern, we try to address the following issues:

Now we want to use object-oriented formal definition calculator, in order to achieve decoupling between the various algorithms. The main use of the classes are as follows:

// 计算类的基类
public abstract class Operation {

    private double value1 = 0;
    private double value2 = 0;

    public double getValue1() {
        return value1;
    }
    public void setValue1(double value1) {
        this.value1 = value1;
    }
    public double getValue2() {
        return value2;
    }
    public void setValue2(double value2) {
        this.value2 = value2;
    }
    protected abstract double getResule();
}

//加法
public class OperationAdd extends Operation {
    @Override
    protected double getResule() {
        return getValue1() + getValue2();
    }
}
//减法
public class OperationSub extends Operation {
    @Override
    protected double getResule() {
        return getValue1() - getValue2();
    }
}
//乘法
public class OperationMul extends Operation {
    @Override
    protected double getResule() {
        return getValue1() * getValue2();
    }
}
//除法
public class OperationDiv extends Operation {
    @Override
    protected double getResule() {
        if (getValue2() != 0) {
            return getValue1() / getValue2();
        }
        throw new IllegalArgumentException("除数不能为零");
    }
}
复制代码

When I want to perform an addition operation, you can use the following code:

public class Main {
    public static void main(String[] args) {
        OperationAdd operationAdd = new OperationAdd();
        operationAdd.setValue1(10);
        operationAdd.setValue2(5);
System.out.println(operationAdd.getResule());
    }
}
复制代码

When I need to perform subtraction, I'm going to create a OperationSub class. In other words, I want to use a different calculation is necessary to create different classes, and to clearly know the name of the class.

Then the work of this repetition can actually create the class into a unified factory class. Simple factory pattern has the following advantages:

1, a caller wanted to create an object, just know that the name on it.

2, shielding concrete realization of the product, the caller only concerned with the interface of the product.

Simple factory pattern implementation

In fact, a simple factory pattern and his name is very simple. Let's look at its composition:

Factory: This is the core of this mode, it contains a certain business logic and arbitration logic. It is often achieved by a concrete class java. (OperationFactory)

Product: It is generally specific products inherit the parent class or implement the interface. In java realized by interfaces or abstract class. (Operation)

ConcreteProduct: object factory class is created instance of this role. Realized by a concrete class java. Be clear to a class diagram showing the relationship between (OperationAdd \ OperationSub etc.) between them under

On the basis of the original class, factory class definitions:

//工厂类
public class OperationFactory {

    public static Operation createOperation(String operation) {
        Operation oper = null;
        switch (operation) {
            case "+":
                oper = new OperationAdd();
                break;
            case "-":
                oper = new OperationSub();
                break;
            case "*":
                oper = new OperationMul();
                break;

            case "/":
                oper = new OperationDiv();
                break;
            default:
                throw new UnsupportedOperationException("不支持该操作");
        }
        return oper;
    }
}
复制代码

With the factory after class, you can use the factory to create an object:

Operation operationAdd = OperationFactory.createOperation("+");
operationAdd.setValue1(10);
operationAdd.setValue2(5);
System.out.println(operationAdd.getResule());
复制代码

A simple factory pattern, users do not need a calculator to realize the relationship between the specific name of that class addition logic, as long as he knows the parameters corresponding to the class "+" on it.

The problem there is a simple factory pattern

When we need to add a calculation, such as square root. This time we need to define a class that inherits Operationclass, which achieved square code. In addition we have to modify the OperationFactorycode for the class, add a case. This is clearly contrary to the principle of opening and closing. One can imagine for adding new products, the factory class is very passive.

Our example is the simplest case. In practical applications, the product is likely to be a multi-level tree structure. Simple factory could not quite apply.

Simple factory pattern summary

Factory class is the key to a simple factory pattern. It contains the necessary logic to determine, based on the information given outside, decide whether the object should be created which specific class. By using the factory class, the outside world can emerge from specific products directly create objects of embarrassment, just need to be responsible for "consumer" objects on it. And do you need these objects exactly how to create and how to organize. Clear the respective responsibilities and rights, help to optimize the entire software architecture.

However, due to factory class focused on creating a logical all instances of violation of the principle of high cohesion allocation of responsibilities, all create a logical focus to a factory class; it can only be created in advance taking into account the class, if you need to add a new class, then we need to change the factory class.

When the system is in specific product categories growing time, there may be requirements created by the factory needs of different instances according to different criteria. This judgment and the judgment of the conditions of the specific type of product intertwined, it is difficult to avoid the spread of module functions, the maintenance and expansion of the system is very unfavorable;

These shortcomings in the factory method pattern to a certain resolve.

Factory Method pattern {# toc_2}

Factory method model (Factory Method Pattern), also known as factory mode, also called virtual constructor (Virtual Constructor) mode or a polymorphic plant (Polymorphic Factory) mode, which belongs to the class created schema.

Mode is a factory method to achieve the concept of object-oriented design patterns "plant." Like other creational patterns, it also deal with the problem in creating an object without specifying the specific type of the object.

Essence factory method pattern is the "definition of a created object's interface, but let's implement this interface to decide which instance of the class factory method to instantiate the class allow deferred to subclasses were."

The method uses factory mode

Factory Method pattern and factory pattern, though they are simple to create objects through the factory, the biggest difference between them is - factory method pattern is designed to complete in full compliance with "the principle of opening and closing."

The method can use the factory mode in the following situations:

A class does not know it needs an object of class: the factory method pattern, the client does not need to know the class name specific product category, you only need to know the corresponding plant to specific product object is created by the concrete factory class; the client needs to know to create product-specific factory class.

A class specified by a subclass which object created: mode method in the factory, the factory for the abstract class only needs to create a product interface, the object can be determined by the subclass to create specific, object-oriented polymorphism and Richter substitution principle, the program is running, an object subclass will override the parent class object, making the system easier to expand.

The task entrusted to create an object of a certain client multiple plants subclass when used without concern for what may be a sub-class factory to create products sub-category, and then dynamically assigned when needed, can be the name of a specific class factory class stored in the configuration file or database.

Factory Method pattern implementation

Factory method pattern includes the following roles:

Product: abstract product Operation( )

ConcreteProduct: specific products ( OperationAdd)

Factory: Abstract Factory ( IFactory)

ConcreteFactory: Concrete Factory ( AddFactory)

There is also an example of using the calculator. Holding Operation, OperationAdd, OperationDiv, OperationSub, OperationMulin the case of several other methods of the same, simple modifications factory class factory mode ( OperationFactory). Replace the original "universal" category of big factories, factory methods used here 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 on the client, you need the following way:

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());
    }
}
复制代码

Here, a factory method pattern has been written.

From the point of view the amount of code, this model factory method is more complex than a simple factory methods. (Operation) The operation for different classes has a corresponding plant. Many people will have the following questions:

Looks like the factory method pattern is much more complex than a simple factory pattern?

Factory Method pattern to create objects and myself no difference? Why we would come up with some factories to?

Here for the above two questions to further understand how the factory method pattern.

Why use the factory to create an object?

Object creation package

In the factory method pattern, factory method to create products needed by customers, but also to customers hides what specific product class will be instantiated this detail, users only need to worry about the plant required for the corresponding product without concern created details, or even know the name of the class specific product category.

Polymorphism plant design is based on the role and character of the product is the key factory method pattern. ** It enables the plant can autonomously determine what product object is created, and how to create the details of the object is completely encapsulated in the concrete factory. ** The reason factory methods is also called polymorphic factory mode, because all of the specific factory classes with the same abstract parent class.

Why each object you want to have a separate factory?

In line with "Open - Closed Principle"

The main purpose is to decouple. When adding new products in the system, no need to modify the interface abstraction abstract factory and product offers without having to modify the client, there is no need to modify other concrete plants and concrete products, and just add a specific plant and specific products on it. Thus, scalability of the system will become very good, full compliance with "the principle of opening and closing.

These are the advantages of factory methods. However, the factory model, there are some unsatisfactory aspects:

When adding a new product, you need to write a new class of specific products, but also to provide the corresponding concrete factory class, the number of pairs of the class system increases, the complexity of the system to some extent, there is more the class needs to be compiled and run, will bring some additional overhead system.

Taking into account the scalability of the system, requires the introduction of abstraction layer, are defined in the abstraction layer using the client code, the system increases the abstraction and the difficulty of understanding, and may need to use the DOM, reflection ART When implemented, increase the difficulty of implementing the system.

Factory Method pattern summary

Factory Method pattern is to further promote the simple and abstract factory pattern.

Due to the use of object-oriented polymorphism, a simple holding mode factory method factory pattern advantages and overcome its shortcomings.

In the factory method pattern, the core of the factory class is no longer responsible for creating all the products, but will work to create a specific subclass to do it. The core classes are given only responsible for plant-specific interfaces that must be implemented, not responsible for the product class is instantiated such details, which makes factory method pattern can allow the system to introduce new products in the plant without modifying role.

The main advantage of the plant model is a method to modify an existing system without adding new class of products, and packaging products of the details of creating an object, the system has good flexibility and scalability; disadvantage that at the same time add new products need to add new plant, resulting in increasing the number of pairs of system classes, increases the complexity of the system to some extent.

Abstract factory pattern {# toc_3}

Abstract Factory (Abstract Factory Pattern): create a series of related or dependent objects interface, without specifying their concrete classes. Abstract Factory pattern, also known as Kit, belonging schema object creation.

Abstract factory model provides a way to separate the plant of the same product family may be encapsulated. In normal use, the client program needs to create a concrete implementation of the abstract factory, and then use the abstract concrete object factory to create the subject as an interface. The client does not need to know (or care) that specific types of objects obtained from the factory in the interior of these methods, since the common interface uses only these client objects. Abstract Factory pattern implementation details a set of objects and their general use separate.

Product Family

To know what is under the product family: the product is in a different hierarchical structure, family functions related to the composition of the product. As in the following example, there are two product families: the family car and commercial vehicle family.

Abstract factory pattern uses

Abstract factory pattern and factory method patterns, are compliant with open - closed principle. But the difference is that the factory method pattern to increase a specific product, to be increased corresponding factory. But the abstract factory pattern only when a new type of product need to add specific plant. That is to say, a factory model factory method can create only one specific product. And a factory abstract factory pattern can create a variety of specific products belong to a class type. The number of factories to create products between simple factory pattern and factory method pattern.

Abstract factory model can be used in the following cases:

A system should not depend on how the product class instance is created, a combination of details and expression, which is important for all types of factory pattern.

System has more than one product family, wherein each time only one product family.

Products belong to the same product family will be used together, the constraints must be reflected in the design of the system.

The system provides a product class library, all of the products appear in the same interface, so that the client does not depend on the specific implementation.

Abstract factory pattern implementation

Abstract Factory pattern includes the following roles:

The method used to declare generate an abstract product: AbstractFactory (Abstract Factory)

ConcreteFactory (particularly plant): abstract factory implements the methods declared abstract products generated, generating a set of specific products that constitute a family of products, each product a product is located in the hierarchical structure;

AbstractProduct (abstract product): a statement for each product interfaces, abstract business methods defined in the abstract product of the product;

Product (product-specific): Define the specific factory production of specific products subject to achieve abstract business methods defined in the interface product.

Examples of this paper, an example of a car foundries making cars. Suppose we are a car foundries, we are responsible for Mercedes and Tesla two companies manufacture the car. We simply understood as the Mercedes-Benz cars need to refuel the car, the car needs to be charged for the Tesla. Which included Mercedes sports cars and commercial vehicles are two, Tesla also include Mercedes-Benz cars and commercial vehicles.

The above scenario, we can put the car and commercial vehicle were treated for sports car factory to create a separate, commercial vehicles have separate factories. In this way, the future is whether any other vendors and then help make cars, sports cars or commercial vehicles as long as we do not need to re-introduction of the factory. Similarly, if we want to add one other types of vehicles, such as SUVs, we do not need to make changes to the car or anything of commercial vehicles.

Here is the abstract products, Mercedes and Tesla cars:

public interface BenzCar {
    //加汽油
    public void gasUp();

}

public interface TeslaCar {
    //充电
    public void charge();
}
复制代码

The following are specific products, Mercedes-Benz sports car, the Mercedes-Benz commercial vehicles, Tesla Roadster, Tesla commercial vehicles:

public class BenzSportCar implements BenzCar {
    public void gasUp() {
        System.out.println("给我的奔驰跑车加最好的汽油");
    }
}

public class BenzBusinessCar implements BenzCar{
    public void gasUp() {
        System.out.println("给我的奔驰商务车加一般的汽油");
    }
}

public class TeslaSportCar implements TeslaCar {
    public void charge() {
        System.out.println("给我特斯拉跑车冲满电");
    }
}

public class TeslaBusinessCar implements TeslaCar {
    public void charge() {
        System.out.println("不用给我特斯拉商务车冲满电");
    }
}
复制代码

Here is the abstract factory:

public interface CarFactory {

    public BenzCar getBenzCar();
    public TeslaCar getTeslaCar();
}
复制代码

The following are specific factory:

public class SportCarFactory implements CarFactory {
    public BenzCar getBenzCar() {
        return new BenzSportCar();
    }

    public TeslaCar getTeslaCar() {
        return new TeslaSportCar();
    }
}

public class BusinessCarFactory implements CarFactory {
    public BenzCar getBenzCar() {
        return new BenzBusinessCar();
    }

    public TeslaCar getTeslaCar() {
        return new TeslaBusinessCar();
    }
}
复制代码

"Opening and closing principle" lopsided

"Principles closing" requires a system open for extension, for the purpose of modifying closed achieve enhanced by extending its function. For systems involving a plurality of product family hierarchical structure with a plurality of products, which includes two enhancements:

Increase product family: to add a new product family, the factory method pattern good support "the principle of opening and closing," added the new product family, only need a corresponding increase in a new concrete factory can be, you do not need to have the code any modifications.

Add a new product hierarchy: For adding new product hierarchy, you need to modify all the factories roles, including abstract factory classes, methods, production of new products in all of the factory class needs to be added, not well supported "opening and closing in principle".

This property is called the abstract factory pattern tilt "of the opening and closing principle", the abstract factory pattern in an oblique way to support the addition of new products, it is easy to increase the availability of a new product family, but not for new product grades this structure provides increased convenience.

Abstract factory pattern summary

Abstract factory pattern provides a create a series of related or dependent objects interface, without specifying their concrete classes. Abstract Factory pattern, also known as Kit, belonging schema object creation.

Abstract factory pattern to all forms of the factory pattern in the most abstract and general a form.

The main advantage of the abstract factory pattern is to isolate a specific class generation, so that the customer does not need to know what is being created, and may create a plurality of objects each time a product family by concrete factory class, or alternatively increased more convenient product family, adding new concrete factory and product family is easy; the main disadvantage is that the addition of new products hierarchical structure is very complex, and the need to modify the abstract factory all the concrete factory class, to support "the principle of opening and closing," the inclination of the presentation.

Three kinds of plant contrastive {# toc_4}

The advantages and disadvantages of simple factory pattern

  • advantage:
    • 1, the specific implementation of shielding products, the caller only concerned with the interface of the product.
    • 2, simple
  • Disadvantages:
    • 1, increase product, you need to modify the factory class, does not meet the open - closed principle
    • 2, factory class focused on creating a logical all instances of violation of the principle of high cohesion allocation of responsibilities

Advantages and disadvantages of the factory method pattern

  • advantage:
    • 1, it inherits the advantages of simple factory pattern
    • 2, conforms to the Open - Closed Principle
  • Disadvantages:
    • 1, increase product, need to add new factory class, resulting in increasing the number of pairs of system classes, increasing the complexity of the system to some extent.

Advantages and disadvantages of the abstract factory pattern

  • advantage:
    • 1, isolating the generation of specific classes, so that customers do not need to know what is being created
    • 2, each class can be created by a plurality of objects a concrete factory product family, product family is increased or alternatively more convenient, to add new concrete factory product family and easy;
  • Shortcoming
    • Adding new products hierarchical structure is very complex, and the need to modify the abstract factory all the concrete factory class, to support "the principle of opening and closing," the inclination of the presentation.

Simple Factory: any product used to produce the same level structure. (For adding new products, mainly new products, it is necessary to modify the factory class in line with the principle of responsibility does not meet a single opening. - closed principle)

Factory method: for producing the same hierarchical structure of the product is fixed. (Support add any product, no need to change the existing factory when new products, the need to increase the product corresponding to a single factory in line with the principles of responsibility, in line with the open - closed principle but introduces complexity.)

Abstract Factory: used to produce different product families of all products. (When adding new products, the plant needs to be modified to increase the product family, the need to increase the plant in line with the principle of single responsibility, partly in line with the open - closed principle, reduced complexity)

Finally, all three models have advantages and disadvantages factory, there is no best, only the most suitable!

Guess you like

Origin juejin.im/post/5ceb3f10f265da1b860864e7