Builder mode of design mode

1. Model motivation

Whether in the real world or in software systems, there are some complex objects that have multiple components, such as a car, which includes various parts such as wheels, steering wheels, and transmitters. For most users, there is no need to know the assembly details of these parts, and they will hardly use a single part, but use a complete car, which can be designed and described through the builder mode, the builder mode Parts can be separated from their assembly process to create a complex object step by step. The user only needs to specify the type of the complex object to get the object without knowing the details of its internal construction.

In software development, there are also a large number of complex objects like cars, which have a series of member attributes, and some of these member attributes are member objects of reference type. Moreover, in these complex objects, there may also be some restrictions. For example, if some attributes are not assigned, the complex object cannot be used as a complete product; the assignment of some attributes must be in a certain order. May not be able to assign values ​​etc.

A complex object is equivalent to a car to be built, and the properties of the object are equivalent to the parts of the car, and the process of building a product is equivalent to the process of combining parts. Because the process of combining components is very complicated, the process of combining these components is often "externalized" into an object called a builder. What the builder returns to the client is a complete product object that has been built, and the user does not need to Concerned about the properties that the object contains and how they are assembled, this is the pattern motivation of the builder pattern.

2. Mode definition

Builder Pattern: The construction of a complex object is separated from its representation, so that the same construction process can create different representations.

The builder pattern is to create a complex object step by step, which allows users to build them only by specifying the type and content of complex objects, and the user does not need to know the specific internal construction details. The builder pattern is an object creation pattern. According to the different Chinese translations, the builder mode can also be called the generator mode.

3. The builder mode includes the following roles:

  • Builder: abstract builder
  • ConcreteBuilder: concrete builder
  • Director: Commander
  • Product: product role

Timing diagram

4. Code example

  1. Builder: abstract builder

    package com.lqs.builder;
    
    public interface Builder {
        // Create part A such as creating a car wheel
        void buildPartA();
    
        // Create part B such as creating a car steering wheel
        void buildPartB();
    
        // Create part C such as creating a car engine
        void buildPartC();
    
        // Returns the final assembled product result (returns the final assembled car)
        // The assembly process of the finished product is not carried out here, but transferred to the Director class below.
        // This enables decoupling of processes and components
        Product getResult();
    }
    
  2. ConcreteBuilder: concrete builder

    package com.lqs.builder;
    
    
    import java.util.Random;
    
    public class ConcreteBuilder implements Builder {
        Product product = new Product();
    
        @Override
        public void buildPartA() {
            product.setNo(new Random().nextInt() + "");
            System.out.println("create parts A");
        }
    
        @Override
        public void buildPartB() {
            product.setBrand("Made by Huawei");
            System.out.println("create parts B");
        }
    
        @Override
        public void buildPartC() {
            product.setName("Yoyomi");
            System.out.println("create parts C");
        }
    
        @Override
        public Product getResult() {
            // Return the result of the final assembled product
            return product;
        }
    }
    
  3. Product: product role

    package com.lqs.builder;
    
    public class Product {
        private String no; // Numbering
        private String brand; // brand
        private String name; // name
    
        public String getNo() {
            return no;
        }
    
        public void setNo(String no) {
            this.no = no;
        }
    
        public String getBrand() {
            return brand;
        }
    
        public void setBrand(String brand) {
            this.brand = brand;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        @Override
        public String toString() {
            return "Product{" +
                    "no='" + no + '\'' +
                    ", brand='" + brand + '\'' +
                    ", name='" + name + '\'' +
                    '}';
        }
    }
    
  4. Director: Commander

    package com.lqs.builder;
    
    public class Director {// for assembling parts
        Builder builder;
    
        public Director(Builder builder) {
            this.builder = builder;
        }
    
        // Compose the parts partA partB partC into a complex object at the end
        // Here is the process of assembling the wheels, steering wheel and engine into a car
        public void construct() {
            builder.buildPartA();
            builder.buildPartB();
            builder.buildPartC();
        }
    }
    
  5. test

    package com.lqs.builder;
    
    public class Test { // call of builder mode
    
        public static void main(String[] args) {
            ConcreteBuilder builder = new ConcreteBuilder();
            Director director = new Director(builder);
            director.construct();
            final Product product = builder.getResult();
            System.out.println(product);
        }
    
    }
    

5. Pattern Analysis

The creation method and return method of the product are defined in the abstract builder class;

The structure of the builder model also introduces a director class Director, which has two main functions: on the one hand, it isolates the customer from the production process; on the other hand, it is responsible for controlling the product generation process. The commander programs for the abstract builder, the client only needs to know the type of the specific builder, and can call the relevant methods of the builder through the commander class, and return a complete product object

In the client code, you don’t need to care about the specific assembly process of the product object, you only need to determine the type of the specific builder. The builder pattern separates the construction of complex objects from the performance of the object, so that the same construction process can be created behave differently.

Six. Advantages

  • In the builder mode, the client does not need to know the details of the internal composition of the product, and the product itself is decoupled from the product creation process, so that the same creation process can create different product objects.
  • Each specific builder is relatively independent and has nothing to do with other specific builders. Therefore, it is easy to replace specific builders or add new specific builders. Users can obtain different product objects by using different specific builders.
  • The product creation process can be controlled more finely. Decomposing the creation steps of complex products into different methods makes the creation process clearer and more convenient to use programs to control the creation process.
  • Adding a new specific builder does not need to modify the code of the original class library. The commander class is programmed for the abstract builder class. The system is easy to expand and conforms to the "open and close principle".

Seven. Disadvantages

  • The products created by the builder mode generally have more in common, and their components are similar. If the products are very different, it is not suitable to use the builder mode, so its scope of use is limited.
  • If the internal changes of the product are complex, it may lead to the need to define many specific builder classes to achieve this change, resulting in a very large system.

8. Pattern application

In many game software, maps include sky, ground, background and other components, and characters include human body, clothing, equipment and other components. You can use the builder mode to design them, and create different types of maps through different specific builders or characters.

9. Schema extension

Simplification of the builder pattern:

  • Omit the abstract builder role: If only one concrete builder is needed in the system, the abstract builder can be omitted.
  • Omit the role of the commander: In the case of only one specific builder, if the role of the abstract builder has been omitted, the role of the commander can also be omitted, so that the role of the Builder can play the dual roles of the commander and the builder.

Ten. Comparison between the builder pattern and the abstract factory pattern

  • Compared with the abstract factory pattern, the builder pattern returns an assembled complete product, while the abstract factory pattern returns a series of related products, which are located in different product hierarchy structures, forming a product family.

  • In the abstract factory mode, the client instantiates the factory class, and then calls the factory method to obtain the required product object, while in the builder mode, the client does not directly call the relevant methods of the builder, but guides through the director class How to generate an object, including the assembly process and construction steps of the object, it focuses on constructing a complex object step by step and returning a complete object.

  • Compared with the abstract factory pattern, the builder pattern returns an assembled complete product, while the abstract factory pattern returns a series of related products, which are located in different product hierarchy structures, forming a product family.

  • In the abstract factory mode, the client instantiates the factory class, and then calls the factory method to obtain the required product object, while in the builder mode, the client does not directly call the relevant methods of the builder, but guides through the director class How to generate an object, including the assembly process and construction steps of the object, it focuses on constructing a complex object step by step and returning a complete object.

  • If the abstract factory pattern is regarded as an auto parts production factory that produces a product family, then the builder pattern is a car assembly factory that can return a complete car through the assembly of components.

Tags: Java Design Pattern

Posted by andre_c on Wed, 11 Jan 2023 05:37:11 +0300