Design Pattern - Builder (Generator) Pattern

Introduction

In this article, we'll introduce the concept, role, and benefits of the Builder pattern, and explore its relationship to other design patterns.

Core Concepts of the Builder Pattern

Insert image description here

Product

A product is a complex object created by a builder that has multiple properties and methods. In the builder pattern, the product is the end result of the builder.

Builder

Builders are the interfaces responsible for building the product. It defines the steps and methods for creating a product, typically including methods for setting properties and returning the final product.

Director

The conductor is the person responsible for coordinating the builders. It guides the builder through the building steps in a specific order to produce the final product.

How Builder Pattern Relates to Other Design Patterns

The Builder pattern is often associated with the following design patterns:

  • Abstract Factory Pattern: The Abstract Factory pattern is used to create a series of interdependent or interrelated objects, while the Builder pattern is used to create complex objects. The difference between the two is that the abstract factory pattern emphasizes the creation of a series of products, while the builder pattern focuses on the creation of a single complex object.
  • Factory Pattern: Factory pattern is used to create different types of objects based on certain conditions, while builder pattern is used to create complex objects. The difference between the two is that the factory pattern emphasizes the selection of object types, while the builder pattern focuses on the assembly process of objects.

Comparison of factory mode and builder mode uml

Insert image description here
Insert image description here

Implementation steps of builder pattern

Here are the steps to implement the builder pattern:

  1. Define the product's properties and methods to ensure the product has the required characteristics.
  2. Create an abstract builder interface that contains methods for creating products and methods for setting product properties.
  3. Create a concrete builder class, implement the builder interface, and implement methods for creating products and setting properties.
  4. Implement a conductor class that receives a builder object and calls the builder's methods in a specific order to build the product.
  5. Write client code, instantiate the conductor and concrete builder objects, and call the conductor's build method to get the final product.

Here is a sample code:

// 产品类
public class Product {
    
    
    private String attribute1;
    private String attribute2;
    
    // 设置属性的方法
    public void setAttribute1(String attribute1) {
    
    
        this.attribute1 = attribute1;
    }
    
    public void setAttribute2(String attribute2) {
    
    
        this.attribute2 = attribute2;
    }
        public void Show(){
    
    
        System.out.println(attribute1);
        System.out.println(attribute2);
    }
    // 其他方法...
}

// 抽象建造者接口
public interface Builder {
    
    
    void buildAttribute1(String attribute1);
    void buildAttribute2(String attribute2);
    Product getResult();
}

// 具体建造者类
public class ConcreteBuilder implements Builder {
    
    
    private Product product;
    
    public ConcreteBuilder() {
    
    
        this.product = new Product();
    }
    
    @Override
    public void buildAttribute1(String attribute1) {
    
    
     System.out.println("设置Attribute1");
        product.setAttribute1(attribute1);
    }
    
    @Override
    public void buildAttribute2(String attribute2) {
    
    
     System.out.println("设置Attribute2");
        product.setAttribute2(attribute2);
    }
    
    @Override
    public Product getResult() {
    
    
        return product;
    }
}

// 指挥者类
public class Director {
    
    
    private Builder builder;

    public Director(Builder builder) {
    
    
        this.builder = builder;
    }

    public void construct() {
    
    
    	System.out.println("指挥建造开始-----------");
        builder.buildAttribute1("Value 1");
        builder.buildAttribute2("Value 2");
        // 还可以按照特定顺序调用其他建造者方法
    }
}

// 客户端代码
public class Client {
    
    
    public static void main(String[] args) {
    
    
        Builder builder = new ConcreteBuilder();
        Director director = new Director(builder);
        
        director.construct();
        
        Product product = builder.getResult();
        product.Show();
        // 使用产品...
    }
}

Insert image description here

Application scenarios of builder pattern

Builder pattern is often used in the following situations:

  • Create complex objects, where the object creation process is complex and requires the participation of multiple steps and components.
  • The construction process of an object needs to be independent of how it is assembled, allowing different builders to be used in the same build process to create different representations.
  • Want to change the internal representation of the product without affecting the overall structure of the product.

Application in spring

In the Spring framework, the application of the builder pattern is mainly reflected in the creation and configuration process of Beans. Spring uses the builder pattern to build and configure various types of beans.

Specifically, the builder pattern in Spring mainly includes the following core components:

  1. ApplicationContext (application context) : In Spring, ApplicationContext is usually used to manage and configure beans. ApplicationContext is responsible for creating and managing Beans, and is responsible for handling Bean dependencies and life cycles. ApplicationContext can configure and create beans through XML configuration files, annotations, or Java code.

  2. BeanDefinitionBuilder : BeanDefinitionBuilder is a builder class provided by Spring for building BeanDefinition (Bean definition). BeanDefinitionBuilder provides a series of methods for configuring various properties and dependencies of the Bean. By calling these methods in a chain, you can set various properties of the BeanDefinition according to your needs.

  3. BeanFactory : BeanFactory is one of Spring's core interfaces, which is responsible for creating and managing Beans. When creating a bean, you usually use the BeanFactory to create the bean instance, configure and initialize it.

  4. XML configuration file : In Spring, you can use XML configuration files to configure and describe Bean information. The elements in the XML configuration file usually correspond to a Bean object. By configuring the attributes and sub-elements of the element, you can set various attributes and dependencies of the Bean.

In the process of using Spring, developers usually use ApplicationContext as the main builder role to create and manage various types of beans by configuring and calling the methods it provides. Developers can use BeanDefinitionBuilder to build Bean definitions and register them in the ApplicationContext to implement customized configuration and build processes for Beans.

To sum up, Spring uses the builder pattern in the process of creating and configuring beans, and implements the construction and configuration of beans through components such as ApplicationContext, BeanDefinitionBuilder, BeanFactory and XML configuration files. Using the builder pattern can simplify the creation and configuration process of beans and improve flexibility and maintainability.

Pros and Cons of Builder Pattern

advantage

  • Separate the build process and representation so that the same build process can create different representations.
  • Flexible configuration options are provided, and clients can freely choose the builder and creation steps according to their needs.
  • Allows changes to the product's internal representation, transparent to client code.

shortcoming

  1. Increased code volume : The builder pattern requires the creation of additional classes such as specific builder classes and commander classes, thus increasing the code volume. The build process may be different for each product, so multiple concrete builder classes may need to be created. Although these additional classes add some overhead, they can improve the maintainability and flexibility of the code.

  2. The assembly sequence requires developer control : In the builder pattern, developers need to control the assembly sequence of the object construction process. If the assembly sequence is incorrect, the product may be assembled incorrectly or parts may be missing. Therefore, developers need to carefully design and control the assembly sequence, increasing the complexity of the design.

Brief summary

The builder pattern encapsulates the object's construction process, separates the construction process and presentation, and provides flexible configuration options. Through the collaboration of abstract builders, concrete builders, and directors, clients can obtain different product representations. However, the builder pattern increases the amount of code and has certain requirements on the build order.

Guess you like

Origin blog.csdn.net/pengjun_ge/article/details/132630195