Detailed explanation of simple factory pattern


Preface

In this article, we take a look at the simple factory pattern, which is the prototype of the design pattern and the beginning of learning the design pattern. I will illustrate its design ideas with examples.


1. Simple Factory Pattern Definition

The simple factory pattern is not one of the 23 design patterns in GoF, but it is generally used as the starting point for learning design patterns. The simple factory pattern, also known as the Static Factory Method Pattern, is a class creation pattern. In the simple factory pattern, instances of different classes can be returned according to different parameters. The simple factory pattern specifically defines a class to be responsible for creating instances of other classes. This class is called a factory class. The created instances usually have a common parent class. The structure of the simple factory pattern is as follows:
Insert image description here
In the pattern structure diagram, Factory represents the factory class, which is the core of the entire pattern and is responsible for implementing the internal logic of creating all instances. The factory class can be called directly from the outside to create the required product objects. There is a static factory method in the factory class that is responsible for producing objects. The system can dynamically decide which instance of the product class should be created based on the parameters passed in by the factory method. The factory method is static and must have a return type. Its return type is an abstract product type, that is, Product type; Product represents an abstract product role. It is the parent class of all objects created by the simple factory pattern and is responsible for defining the common features of all instances. The public interface of ConcreteProduct represents a specific product role, which is the creation target of the simple factory pattern. All created objects are instances of a specific class that plays this role. There are generally multiple ConcreteProduct classes in a system, and each specific product corresponds to a Concrete class.

2. Give an example

We design a Coffee (coffee class), which is an abstract class. For example, there are two specific coffees, American Coffee and Latte Coffee. Therefore, we need a specific factory to create specific coffee products. Let's define a factory that produces coffee, SimpleCoffeeFactory. Their pattern structure diagram is as follows:
Insert image description here
AmericanCoffee and LatteeCoffee need to inherit the abstract product Coffee, and at the same time implement the abstract methods in Coffee, such as getting the coffee name, adding milk, adding sugar, etc., and SimpleCoffeeFactory is a factory that produces coffee. It needs to provide a static method for creating coffee. At the same time, the return value type of this method must be the Coffee abstract class. This reflects the polymorphic feature, that is, the parent class reference can point to the subclass object.
The relevant code is as follows:
The abstract coffee class can actually be an interface. What I defined is an abstract class:

abstract public class Coffee {
    
    

    abstract protected void getName();

    abstract protected void addMilk();

    abstract protected void addSugar();
}

Americano coffee (specific products):

public class AmericanCoffee extends Coffee{
    
    

    @Override
    protected void getName() {
    
    
        System.out.println("American Coffee...");
    }

    @Override
    protected void addMilk() {
    
    
        System.out.println("add American coffee milk...");
    }

    @Override
    protected void addSugar() {
    
    
        System.out.println("add American coffee sugar...");
    }
}

Latte (specific products):

public class LatteCoffee extends Coffee{
    
    


    @Override
    protected void getName() {
    
    
        System.out.println("Latte Coffee...");
    }

    @Override
    protected void addMilk() {
    
    
        System.out.println("add Latte Coffee milk...");
    }

    @Override
    protected void addSugar() {
    
    
        System.out.println("add Latte Coffee sugar...");
    }
}

Coffee factory category:

public class SimpleCoffeeFactory {
    
    

    public static Coffee createFactory(String type){
    
    
        Coffee coffee = null;
        if ("AmericanCoffee".equals(type)){
    
    
            coffee = new AmericanCoffee();
        } else if ("LatteeCoffee".equals(type)) {
    
    
            coffee = new LatteCoffee();
        }
        return coffee;
    }
}

A static method for creating coffee is defined in the coffee factory class. The input parameter is the type of coffee, and a specific coffee object is returned based on the type judgment.
You can create a coffee shop class externally and call the static methods provided by the factory to create specific coffee:

public class CoffeeStory {
    
    

    public static void main(String[] args) {
    
    
        orderCoffee("AmericanCoffee");
    }

    public static Coffee orderCoffee(String name){
    
    
        SimpleCoffeeFactory simpleCoffeeFactory = new SimpleCoffeeFactory();
        Coffee coffee = simpleCoffeeFactory.createFactory(name);
        coffee.getName();
        coffee.addMilk();
        coffee.addSugar();
        return coffee;
    }
}

3. Disadvantages of the simple factory model

In the simple factory pattern, the factory class contains the necessary judgment logic to decide when to create which instance of the product class. The client can be exempted from the responsibility of directly creating product objects and only "consume" the product. The simple factory pattern uses this This method realizes the division of responsibilities. However, since the factory class concentrates all product creation logic, once it fails to work properly, the entire system will be affected; at the same time, system expansion is difficult. Once a new product is added, the factory logic has to be modified, which violates the open-close principle. For example, in the above case, if we add another type of Italian coffee, the code logic of the static factory method needs to be changed while creating a specific product class. Therefore, the simple factory pattern has many problems and is usually not used in actual development.


Summarize

In this article, we illustrate the design principles of the simple factory pattern and the roles it contains based on actual cases. Next, we continue to look at another factory method pattern with a more reasonable design.

おすすめ

転載: blog.csdn.net/qq_40187702/article/details/131735715