Design Pattern - Builder Pattern

1 Definition

Official Definition: Separating the construction of complex objects from their representations so that the same construction process can create different representations.

Personally, I understand that when creating an object, many steps are required, and these steps are basically unchanged. For example, drawing a figure, torso, limbs, head, and seven orifices on the head, the basic composition of a person is fixed. , we abstract the steps into a builder interface or abstract class. To generate this object, hand it over to the builder to build it, and the builder can directly get it and express it.

2 Structure and Implementation

The builder pattern structure diagram is as follows:

The builder mode consists of four elements: product, abstract builder, concrete builder, and conductor. The commander can sometimes not, as explained in Section 6.2 of the following code.

The main roles of the Builder mode are as follows:

1. Product: It is a complex object containing multiple components, each of which is created by a specific builder.

2. Abstract Builder (Builder): It is an interface that contains abstract methods for creating various sub-components of a product, and usually also contains a method getProduct() that returns a complex product (Product).

3. Concrete Builder: Implement the Builder interface to complete the specific creation method of each component of the complex product.

4. Director (Director): It calls the component construction and assembly methods in the builder object to complete the creation of complex objects, and does not involve specific product information in the director.

3 Advantages and disadvantages

3.1 Advantages

1. Good encapsulation, separation of construction and presentation.

2. Good scalability, each specific builders are independent of each other, which is conducive to the decoupling of the system.

3. The client does not need to know the details of the internal composition of the product, and the builder can gradually refine the creation process without any impact on other modules, which is convenient for controlling the risk of details.

3.2 Disadvantages

1. The components of the product must be the same, which limits the scope of its use.

2. If the internal changes of the product are complicated, if the internal changes of the product occur, the builder must also modify it simultaneously, and the maintenance cost in the later period is relatively large.

4 Applicable scenarios

1. The same method, different execution order, produces different results.

2. Multiple components or parts can be assembled into an object, but the results are not the same.

3. The product class is very complex, or different calling sequences in the product class have different effects.

4. Initializing an object is particularly complicated, with many parameters, and many parameters have default values.

5 The difference between the builder pattern and the factory pattern

The only difference between the builder pattern and the factory pattern is for the creation of complex objects. That is, if you create simple objects, you usually use the factory pattern to create them, and if you create complex objects, you can consider using the builder pattern.

Specifically, there are the following differences:

1. The builder pattern pays more attention to the calling sequence of methods, and the factory pattern focuses on creating objects.

2. The strength of creating objects is different. The builder mode creates complex objects, which are composed of various complex components. The objects created by the factory mode are all the same.

3. The focus is different. The factory pattern only needs to create the object, while the builder pattern not only needs to create the object, but also knows which components the object is composed of.

4. The builder mode is different according to the order in the construction process, and the final object components are also different.

6 Code Examples

The code example includes two parts, one part is the builder pattern formed by Director, Builder and Product, and the other part is the construction of parts disordered assembly through static inner class.

6.1 Builder pattern formed by Director, Builder and Product

Computer (product) assembly, there are motherboard, CPU, memory, hard disk, case shell, five steps, the builder Foxconn is responsible for assembling for us, Lenovo is our commander, we do not need to buy a computer from Foxconn, but to Lenovo.

6.1.1 Computer Products Computer

/**
 * @program: design-pattern-learning
 * @author: zgr
 * @create: 2021-09-26 11:08
 **/
public class Computer {
    List<String> components = new ArrayList<>();

    public void show(){
        System.out.println("computer include: ");
        for (String s: components) {
            System.out.println(s);
        }
    }
}

6.1.2 Assembling computer abstract interface ComputerBuilder

/**
 * @program: design-pattern-learning
 * @author: zgr
 * @create: 2021-09-26 11:11
 **/
public interface ComputerBuilder {

    /**
     * 组装主板
     */
    void constructBoard();

    /**
     * 组装cpu
     */
    void constructCpu();

    /**
     * 组装内存条
     */
    void constructMemory();

    /**
     * 组装硬盘
     */
    void constructHardDisk();

    /**
     * 组长机箱壳
     */
    void constructCase();

    /**
     * 返回电脑成品
     * @return 电脑
     */
    Computer getComputer();
}

6.1.3 Specific Builder Foxconn Builder

/**
 * @program: design-pattern-learning
 * @author: zgr
 * @create: 2021-09-26 11:20
 **/
public class FoxconnBuilder implements ComputerBuilder{

    private Computer computer = new Computer();

    @Override
    public void constructBoard() {
        computer.components.add("lenovo board");
    }

    @Override
    public void constructCpu() {
        computer.components.add("lenovo cpu");
    }

    @Override
    public void constructMemory() {
        computer.components.add("lenovo memory");
    }

    @Override
    public void constructHardDisk() {
        computer.components.add("lenovo hard disk");
    }

    @Override
    public void constructCase() {
        computer.components.add("lenovo case");
    }

    @Override
    public Computer getComputer(){
        return computer;
    }
}

6.1.4 Lenovo Director Lenovo Director

/**
 * @program: design-pattern-learning
 * @author: zgr
 * @create: 2021-09-26 11:31
 **/
public class LenovoDirector {

    private ComputerBuilder computerBuilder;

    public LenovoDirector(ComputerBuilder computerBuilder){
        this.computerBuilder = computerBuilder;
    }


    public Computer getComputer(){
        computerBuilder.constructBoard();
        computerBuilder.constructCpu();
        computerBuilder.constructMemory();
        computerBuilder.constructHardDisk();
        computerBuilder.constructCase();

        return computerBuilder.getComputer();
    }
}

6.1.5 Main function

public class MainClass {
    public static void main(String[] args) {
        LenovoDirector lenovoDirector = new LenovoDirector(new FoxconnBuilder());
        Computer computer = lenovoDirector.getComputer();
        computer.show();
    }
}

6.1.6 Running Results

6.2 The static inner class method realizes the structure of parts out of order assembly

Mobile phone (product) assembly, there are four steps: motherboard, CPU, storage, mobile phone case, the builder Quanta is responsible for assembling for us, apple directly asks Quanta to pick up the phone to get the mobile phone, no commander, Quanta assembles the mobile phone in four steps Can be exchanged as needed. 

6.2.1 Mobile Phone Products Telephone

/**
 * @program: design-pattern-learning
 * @author: zgr
 * @create: 2021-09-26 11:08
 **/
public class Telephone {
    List<String> components = new ArrayList<>();

    public void show(){
        System.out.println("telephone include: ");
        for (String s: components) {
            System.out.println(s);
        }
    }
}

6.2.2 Assembling the mobile phone abstract interface TelephoneBuilder

/**
 * @program: design-pattern-learning
 * @author: zgr
 * @create: 2021-09-26 12:06
 **/
public interface TelephoneBuilder {

    /**
     * 组装主板
     * @return 手机构建者
     */
    TelephoneBuilder constructBoard();

    /**
     * 组装cpu
     * @return 手机构建者
     */
    TelephoneBuilder constructCpu();

    /**
     * 组装存储
     * @return 手机构建者
     */
    TelephoneBuilder constructMemory();

    /**
     * 组长手机壳
     * @return 手机构建者
     */
    TelephoneBuilder constructCase();

    /**
     * 返回电脑成品
     * @return 电脑
     */
    Telephone getTelephone();
}

6.2.3 QuantaBuilder

/**
 * @program: design-pattern-learning
 * @author: zgr
 * @create: 2021-09-26 12:04
 **/
public class QuantaBuilder implements TelephoneBuilder{
    private Telephone telephone;

    public QuantaBuilder(){
        this.telephone = new Telephone();
    }

    @Override
    public TelephoneBuilder constructBoard() {
        telephone.components.add("apple board");
        return this;
    }

    @Override
    public TelephoneBuilder constructCpu() {
        telephone.components.add("apple cpu");
        return this;
    }

    @Override
    public TelephoneBuilder constructMemory() {
        telephone.components.add("apple memory");
        return this;
    }

    @Override
    public TelephoneBuilder constructCase() {
        telephone.components.add("apple case");
        return this;
    }

    @Override
    public Telephone getTelephone() {
        return telephone;
    }
}

6.2.4 Main function

/**
 * @program: design-pattern-learning
 * @author: zgr
 * @create: 2021-09-26 11:08
 **/
public class MainClass {
    public static void main(String[] args) {
        QuantaBuilder quantaBuilder = new QuantaBuilder();
        Telephone telephone = quantaBuilder.
                constructBoard()
                .constructMemory()
                .constructCpu()
                .constructCase()
                .getTelephone();
        telephone.show();
    }
}

6.2.5 Running Results

6.3 Summary

There are two code implementations. The first one has a commander, which is suitable for the case where the construction steps are unchanged. The second one is a flexible implementation of static inner classes, and there is no special requirement for the sequence of each step. 

7 Quotes

1. "Dahua Design Patterns"

2. Understand the Builder pattern of design patterns in seconds

3. Detailed explanation of the builder mode (Bulider mode)

4. Java Design Patterns - Builder Pattern

8 Source code

design-pattern-learning/src/com/hz/design/pattern/builder at main · airhonor/design-pattern-learning · GitHub

Guess you like

Origin blog.csdn.net/honor_zhang/article/details/120488777