Java is really not difficult (thirty-one) builder mode

builder mode

1. What is Builder Mode?

We know that in the process of software development, it is sometimes necessary to create a very complex object, which is usually composed of multiple sub-components in certain steps.

For example, when we assemble a computer by ourselves, we need to assemble components such as CPU, motherboard, memory, hard disk, graphics card, chassis, monitor, keyboard, mouse and so on. For example, the school needs to purchase 100 computers. The school cannot buy the parts and assemble it by itself. It must tell the buyer what kind of configuration it needs, and then the buyer will go to the computer company to buy it, and the company will help you assemble it and then hand it over to the buyer. , and finally to the school.

The above example shows that each component can be flexibly selected (including the grades of various configurations of the computer), but the creation steps are similar. However, the creation of this type of product cannot be described by the factory pattern introduced earlier, only the builder pattern can describe the creation of this type of product well.


2. Definition of Builder Pattern

Definition of Builder Pattern:

Separating the construction of a complex object from its representation so that the same construction process can create different representations is called the builder pattern. It is a complex object decomposed into multiple simple objects, and then built step by step. It separates change from change, that is, the components of the product are unchanged, but each part can be flexibly selected.

In one sentence: decouple the construction of a complex object from its representation, so that the same construction process can create different representations

Type: Create Class Pattern


3. Advantages and disadvantages of the builder mode

advantage:

  1. Good encapsulation, separation of build and presentation
  2. The scalability is better, and each specific builder is 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. The builder can gradually refine the creation process without any impact on other modules, which is easy to control the risk of details

shortcoming:

  1. The components of the product must be the same, which limits its scope of use
  2. If the internal changes of the product are complex, if the internal changes of the product occur, the builder must also modify it synchronously, and the maintenance cost in the later period is relatively large.

Notice:

The builder pattern and the factory pattern have different concerns: the builder pattern focuses on the assembly process of components, while the factory method pattern focuses more on the component creation process, but the two can be used in combination.


4. The structure of the builder pattern

The main roles of the Builder mode are as follows:

  1. Product role (Product): It is a complex object containing multiple components, and its individual components are created by a specific builder
  2. Abstract Builder: Implements the Builder interface to construct and assemble the various components of the product, defines and clarifies the representation it creates, and provides an interface for retrieving the product
  3. Concrete Builder: Constructs an object using the Builder interface to guide the construction process
  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

Structure diagram (referenced from the Internet):
insert image description here


5. Builder mode code demonstration

For example, now you need to build a car:

Product category:

/**
 * 产品类
 */
public class Car {
    
    

    //车的建造过程

    private String wheel;  //车轮
    private String skeleton;  //车架
    private String engine;   //发动机


    public String getWheel() {
    
    
        return wheel;
    }

    public void setWheel(String wheel) {
    
    
        this.wheel = wheel;
    }

    public String getSkeleton() {
    
    
        return skeleton;
    }

    public void setSkeleton(String skeleton) {
    
    
        this.skeleton = skeleton;
    }

    public String getEngine() {
    
    
        return engine;
    }

    public void setEngine(String engine) {
    
    
        this.engine = engine;
    }
}

Instructor class:

/**
 * 指导者
 */

//汽车总监
public class CarDirector {
    
    

    public Car constructCar(ICarBuilder builder){
    
    
        builder.buildwheel();
        builder.buildSkeleton();
        builder.buildEngine();

        return builder.buildCar();
    }
}

Specific builder:

/**
 * 具体建造者:生产具体的东西
 */

public class ConcreteBuilder implements ICarBuilder{
    
    


    Car car;

    public ConcreteBuilder(){
    
    
        car = new Car();
    }

    @Override
    public void buildwheel() {
    
    
        car.setWheel("轮子");
    }

    @Override
    public void buildSkeleton() {
    
    
        car.setSkeleton("车身结构");
    }

    @Override
    public void buildEngine() {
    
    
        car.setEngine("发动机");
    }

    @Override
    public Car buildCar() {
    
    
        return this.car;
    }
}

Abstract builder (interface):

/**
 * 抽象建造者
 */
public interface ICarBuilder {
    
    

    public void buildwheel();   //构建车轮
    public void buildSkeleton();   //构建骨架
    public void buildEngine(); //构建发动机

    Car buildCar();

}

Test class:

public class Test {
    
    

    public static void main(String[] args){
    
    

        //新建一个总监(替你去买汽车)
        CarDirector director = new CarDirector();

        Car car = director.constructCar(new ConcreteBuilder());

        System.out.println(car.getWheel());
        System.out.println(car.getEngine());
        System.out.println(car.getSkeleton());
    }
}

After reading the code demonstration and then combining the first part of the article, you can understand it! !


6. Application scenarios of the builder mode

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

Main application scenarios:

  1. The same method, different execution order, produces different results
  2. Multiple assemblies or parts can be assembled into one object, but produce different results
  3. The product class is very complex, or different calling sequences in the product class have different effects
  4. Initializing an object is particularly complex, with many parameters, and many parameters have default values

7. The difference between the builder pattern and the factory pattern

  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 parts the object is composed of.
  4. The builder mode is different according to the order in the construction process, and the final object component composition is also different

insert image description here

Guess you like

Origin blog.csdn.net/m0_57310550/article/details/123723068