Small talk on design patterns (2)—Simple factory pattern

Column introduction

Column address

link

Column introduction

It mainly analyzes and summarizes the 23 common design patterns currently on the market one by one. I hope that interested friends can take a look and it will be continuously updated. I hope you can supervise me and we can learn and make progress together. Come on, everyone.
Insert image description here

Simple factory pattern

The Simple Factory Pattern is a creational design pattern that provides the best way to create objects. By encapsulating the creation logic of the object in a factory class, the client does not need to know the specific creation details. , just request the required object from the factory class.

Simple factory pattern composition

In the simple factory pattern, there are three main roles involved: abstract products, concrete products and simple factories.

Abstract Product

Abstract product is the common interface of specific product classes, which defines the common methods of the product. An abstract product can be an interface or abstract class, and the specific implementation is completed by the specific product class.

Concrete Product

A concrete product is an implementation class of an abstract product, which implements the methods defined in the abstract product. In the simple factory pattern, each specific product corresponds to a specific product category.

Simple Factory

A simple factory is a class that contains static methods that create product objects. It creates the corresponding specific product object according to the client's request and returns it to the client for use. A simple factory hides the details of object creation. The client only needs to obtain the required objects through the factory class without directly instantiating the specific product class.
Insert image description here

The relationship between the three

1. Abstract products standardize the behavior of specific products by defining the common interface of the product.
2. The specific product is the implementation class of the abstract product and is responsible for implementing the methods defined in the abstract product.
3. As a factory class, the simple factory encapsulates the object creation process. It creates the corresponding specific product object according to the client's request and returns it to the client for use.

main idea

Encapsulate the object creation process in a factory class, and the client only needs to obtain the required object through the static method of the factory class without directly instantiating the specific product class. This can reduce the coupling between the client and specific product categories, and facilitate the expansion and maintenance of product types.
Insert image description here

Java code implementation

First, we define an abstract product interface Product, which contains an abstract method use():

public interface Product {
    
    
    void use();
}

Then, we create two concrete product classes, ProductA and ProductB, which implement the abstract product interface Product:

public class ProductA implements Product {
    
    
    @Override
    public void use() {
    
    
        System.out.println("Product A is being used.");
    }
}

public class ProductB implements Product {
    
    
    @Override
    public void use() {
    
    
        System.out.println("Product B is being used.");
    }
}

Insert image description here

Next, we create a simple factory class SimpleFactory, which contains a static method createProduct(String type) to create the corresponding product object according to the passed parameter type:

public class SimpleFactory {
    
    
    public static Product createProduct(String type) {
    
    
        if (type.equals("A")) {
    
    
            return new ProductA();
        } else if (type.equals("B")) {
    
    
            return new ProductB();
        }
        return null;
    }
}

Finally, we can use the simple factory pattern in client code to create concrete product objects:

//客户端
public class Client {
    
    
    public static void main(String[] args) {
    
    
        Product productA = SimpleFactory.createProduct("A");
        productA.use();  // Output: Product A is being used.

        Product productB = SimpleFactory.createProduct("B");
        productB.use();  // Output: Product B is being used.
    }
}

Insert image description here

code analysis

The client creates a specific product object by calling the SimpleFactory.createProduct() method without directly instantiating the specific product class. In this way, the coupling between the client and specific products is reduced, and it also facilitates the expansion and maintenance of product types.

The simple factory class SimpleFactory contains a static method createProduct(String type), which creates the corresponding product object according to the passed parameter type. In actual applications, more complex logic can be used to create objects based on specific needs, such as reading configuration files or databases to determine which specific product to create.

In the client code, we create the specific product object by calling the SimpleFactory.createProduct() method. The client only needs to know the type of product and does not need to care about the specific creation details. This can reduce the coupling between the client and specific product categories, and facilitate the expansion and maintenance of product types.

Advantages and Disadvantages Analysis

advantage

Encapsulates the object creation process

The simple factory pattern encapsulates the object creation process in a factory class. The client only needs to know the type of product and does not need to care about the specific creation details. This can reduce the complexity of the client and facilitate the expansion and maintenance of product types.

Reduces the coupling between the client and specific product categories

The client only needs to obtain the required objects through the factory class without directly instantiating the specific product class. This can reduce the dependency between the client and specific product classes, making the client code more flexible and maintainable.
Insert image description here

Facilitates expansion and maintenance of product types

In the simple factory pattern, if you need to add a new product type, you only need to modify the code of the factory class. This makes it easy to add new product types without modifying client code. At the same time, it also facilitates the maintenance of product types and centrally manages the object creation process.

shortcoming

Violates the open-close principle

In the simple factory pattern, when adding a new product type, the code of the factory class needs to be modified. This violates the open-closed principle, and modifying existing code may introduce new risks. Therefore, if the product type changes frequently, the simple factory pattern is not suitable.

Factory responsibilities are too heavy

In the simple factory pattern, the factory class is responsible for creating all product objects. As the types of products increase, the code of the factory class will become more and more complex and have overloaded responsibilities. This violates the single responsibility principle and is not conducive to code maintenance and expansion.

Summarize

The simple factory pattern is a simple and commonly used creational design pattern, suitable for scenarios where there are fewer and relatively simple objects to create. It encapsulates the object creation process, reduces the complexity of the client, and facilitates the expansion and maintenance of product types. However, the simple factory model violates the open-close principle and is not suitable for situations where product types change frequently. In addition, the overloaded responsibilities of the factory class are also one of its shortcomings. Therefore, in practical applications, it is necessary to choose the appropriate creation mode according to the specific situation.

Insert image description here

Guess you like

Origin blog.csdn.net/weixin_74888502/article/details/132873745