Model motivation

The simple factory pattern, discussed in detail in the previous article, provides only one factory class, which results in:

It was covered in detail in the last article, so here’s a review

  • The factory class must be modified whenever a new product is to be produced in the factory, which clearly violates the open and close principle of object-oriented design.
  • All products are created by the same factory, the factory class has heavy responsibility, and the coupling degree between specific products and factory class is high, which seriously affects the flexibility and expansibility of the system.

Based on the above two points, the factory method model is derived, which can solve these problems well.

🚄 To return to the scenario compared above, there are all kinds of mobile phones in mobile phone collection stores/private stores, just like a simple factory model, but the whole store operation model will be bloated, and the services provided may be very amateur, which is why the existence of flagship stores is meaningful.

Suppose a collection store originally sold mobile phones of Huawei, Apple and Samsung, then we changed it into three exclusive stores: Huawei store, Apple store and Samsung store, each of which only sells mobile phones of its own brand, are all concrete subclasses of abstract mobile phone store category.

In this way, once a new brand phone such as Xiaomi is introduced, it only needs to build a Xiaomi exclusive store, which can exclusively provide Xiaomi phones.

This mode is the factory method mode, which undoubtedly makes the factory mode superior to the simple factory mode and more in line with the “open and close principle”.

define

The Factory method pattern is also called the Factory pattern and the Virtual Constructor pattern or the Polymorphic Factory pattern, which belongs to the creation pattern.

Parent in factory method pattern, the factory is responsible for defining public interfaces, objects created products and factories subclass object is responsible for generating the specific products, the purpose is to delay product class instantiation operations to complete, factory subclasses by factory subclasses to determine exactly which a specific product class to instantiate.

The factory method pattern is a further abstraction and extension of the simple factory pattern. The factory method pattern retains the advantages of the simple factory pattern and overcomes its disadvantages by using object-oriented polymorphism. The core factory class no longer takes care of the creation of all products, leaving the specific creation to subclasses, which allows the factory method pattern to allow the system to introduce new products without modifying the factory role.

UML class diagrams

The model structure

The factory method pattern contains the following roles:

  • ProductAbstract product
  • ConcreteProduct: Specific products
  • FactoryAbstract factory
  • ConcreteFactory: Specific factory

More instances

The sample code

Product.java

public abstract class Product {
    public abstract void use(a);
}
Copy the code

ConcreteProductA.java

public class ConcreteProductA extends Product{
    @Override
    public void use(a) {
        // TODO: useProductA}}Copy the code

ConcreteProductB.java

public class ConcreteProductB extends Product{
    @Override
    public void use(a) {
        // TODO: useProductB}}Copy the code

Factory.java

public abstract class Factory {
    public abstract Product factoryMethod(a);
}
Copy the code

ConcreteFactoryA.java

public class ConcreteFactoryA extends Factory {
    @Override
    public Product factoryMethod(a) {
        return newConcreteProductA(); }}Copy the code

ConcreteFactoryB.java

public class ConcreteFactoryB extends Factory {
    @Override
    public Product factoryMethod(a) {
        return newConcreteProductB(); }}Copy the code

The advantages and disadvantages

In the foreground factory method pattern, the factory method is used to create the desired product. It also hides from the customer the details of which specific product class will be instantiated. Users need only care about the factory for the desired product, not the creation details, or even the name of the specific product class.

➤ The design of polymorphism based on the factory role and product role is the key to the factory methodology pattern. It enables the factory to decide which product object to create, and the details of creating this object are completely encapsulated within the specific factory. The factory method pattern is also called polymorphic factory pattern because all concrete factory classes have the same abstract parent class.

✔ When you add new products to the system, you don’t need to modify the abstract factory and the abstract method provided by the abstract product. You don’t need to modify the client. You don’t need to modify other specific factories and products. The scalability of the system becomes good and fully conforms to the “open and closed principle”.

❌ when adding new products, it is necessary to write new specific product classes and provide corresponding specific factory classes. The number of classes in the system will increase in pairs, which increases the complexity of the system to a certain extent and brings extra overhead to the system.

❌ Considering the scalability of the system, an abstraction layer is introduced, which is defined in the client code, increasing the abstraction and difficulty of understanding the system.

Applicable scenario

Use the factory method pattern in the following cases:

  • 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, only the corresponding factory, and the specific product object is created by the corresponding concrete factory class. The client needs to know the factory class to create the specific product.
  • A class through its subclasses to specify which object to be created, for the abstract factory class only need to provide an interface for creating products, and by its subclasses to determine specific to create the object, using the object-oriented polymorphism and magnitude of the substitution principle, when the program is run by a subclass overrides the superclass object, so as to make the system more scalable.
  • Delegate the task of creating objects to one of multiple factory subclasses. The client can use it without worrying about which factory subclass creates the product subclass and specify it dynamically when necessary. The class name of the specific factory class can be stored in the configuration file or database.

Application of factory method pattern in JDK

(1) Factory method in JDBC

// Factory
Connection conn = DriverManager.getConnection("jdbc:microsoft:sqlserver://localhost:1433; DatabaseName = DB; user = root; password = root");
// Product
Statement statement = conn.createStatement();
// execute product's method
ResultSet rs = statement.executeQuery("select * from UserInfo");
Copy the code

(2) The iterator() method of the java.util.collection interface

ArrayList and LinkedList classes to understand how Collection implements the factory method pattern:

  • ArrayList.java

  • LinkedList.java

Model extension

  • Use multiple factory methods: Multiple factory methods can be defined in an abstract factory role to enable specific factory roles to implement these different factory methods, which can contain different business logic to meet the needs of different product objects.
  • Reuse of product objects: Factory objects can store created products in a collection (such as groups, lists, and so on) and then query the collection based on customer requests for products. If there is a product object that meets the requirements, the product is returned directly to the client. If there is no such product object in the collection, a new satisfying product object is created, which is then added to the collection and returned to the client.
  • Loss of polymorphism and degradation of patternsIn general, factory objects should have abstract parent types. If there is only one concrete factory class in the factory hierarchy, the abstract factory is omitted, and factory methods are designed to be static, and the factory method pattern is degradedSimple Factory model.

The last

👆 Previous: “Design Patterns” 🌇 Simple Factory Pattern

👇 Next article: Continuing article, please look forward to…

❤️ Good code without explanation, pay attention to the “rip design patterns” column, with me to learn design patterns, your code can be as elegant as poetry!

❤️ / END/If this article is helpful to you, click a “like” to support it, your support is my biggest motivation!