Why should we use the factory model? Isn't it easy to create an object using new? The first in the valid tive is to use the static factory method instead of the constructor. It provides the following reasons:
1. The static factory method calls a clear method name when creating an object, which can be easily read by programmers.
2. The factory method allows you to create objects flexibly. For example, you can control the number of objects and return any type of subclass objects.
3. Code can be simplified when you create a parameterized instance type.
According to the information on the Internet, there are three factory models: simple factory model (static factory model), factory method model and abstract factory model.
I. Simple factory Model
Let's take a look at the class diagram:
In this way, the factory can call two methods to create Aclass and bclass instances. However, the simple factory mode does not strictly follow the "open and closed" principle. When a cClass occurs, we need to modify the factory class to meet the requirements for creating a cClass instance.
Ii. Factory method mode
The factory method mode is an improvement of the simple factory mode to meet the requirements of the "Open and Close" principle. The basic idea is to create a "Factory" Production Line for each class, so that when I add a class, I only need to create a "Factory" to encapsulate changes. Its Class diagram is as follows:
Iii. Abstract Factory Model
The factory method model already meets the "open and closed" principle, but a factory can only produce one product, but in reality, classes may be classified according to different dimensions. For example, BMW and Mercedes-Benz both have commercial vehicles and sports cars. According to the classification of automobile brands, we can build two factories, one factory specializing in the production of BMW cars, and the other factory specializing in the production of Mercedes-Benz cars. Similarly, we can classify cars by type. A factory produces commercial vehicles and a factory can produce sports cars. Abstract Factory mode a factory can produce the same type of products.
Take the first example. The class diagram is as follows:
Factory model of Design Pattern