Statement: For reprint, please attach the link to the original text

Tip: The title sequence starts with 4, which corresponds to the order in which the various design pattern notes are published. For example, in the first article, the prototype pattern, a common Java design pattern for beginners, starts with 3.

4. Builder Mode (common)

4.1 Introduction to the Builder model

  • Builder Pattern

    • Using multiple simple objects to build a complex object step by step, separating the construction of a complex object from its representation so that the same construction process can create different representations
    • Allows users to build complex objects simply by specifying their type and content, without knowing the specific build details inside
  • Scenario, for example,

    • FC set meal creation: Set meal is a complex object, which generally consists of staple food such as hamburger, grilled wings and drinks such as juice and coke. Different sets have different combinations, and KFC waiters can assemble these components step by step according to customers’ requirements to construct a complete set meal
    • Computer with low, high, assembly needs CPU, memory, power supply, hard disk, motherboard and so on
  • The core of

    • Builder: Abstract Builder that defines multiple common methods and build methods
    • ConcreteBuilder: ConcreteBuilder
    • Director: The Director who controls the composition process and hands the requirements to the builder, who creates the objects
    • Product: Product role

    Let’s look at the picture again:

4.2 Builder model case

Create product class Computer first:

/ * * *@Auther: csp1999
 * @Date: 2020/11/08 / would *@Description: Computer */
public class Computer {
    private String cpu;
    private String memory;
    private String mainboard;
    private String disk;
    private String power;

    public String getCpu(a) {
        return cpu;
    }

    public void setCpu(String cpu) {
        this.cpu = cpu;
    }

    public String getMemory(a) {
        return memory;
    }

    public void setMemory(String memory) {
        this.memory = memory;
    }

    public String getMainboard(a) {
        return mainboard;
    }

    public void setMainboard(String mainboard) {
        this.mainboard = mainboard;
    }

    public String getDisk(a) {
        return disk;
    }

    public void setDisk(String disk) {
        this.disk = disk;
    }

    public String getPower(a) {
        return power;
    }

    public void setPower(String power) {
        this.power = power;
    }

    @Override
    public String toString(a) {
        return "Computer{" +
                "cpu='" + cpu + '\' ' +
                ", memory='" + memory + '\' ' +
                ", mainboard='" + mainboard + '\' ' +
                ", disk='" + disk + '\' ' +
                ", power='" + power + '\' ' +
                '} '; }}Copy the code

Next create the Abstract Builder interface Builder:

/ * * *@Auther: csp1999
 * @Date: 2020/11/08/10:38
 * @DescriptionThe abstract builder interface * * declares the builder's public method */
public interface Builder {

    /** * interface method */
    void buildCpu(a);

    void buildMainBoard(a);

    void buildDisk(a);

    void buildPower(a);

    void buildMemory(a);

    Computer createComputer(a);
}
Copy the code

Then create the concrete builder class A (high powered computer builder)HighComputerBuilder and the concrete builder class B(low powered computer builder) LowComputerBuilder:

/ * * *@Auther: csp1999
 * @Date: 2020/11/08 / they *@Description: Specific builder A: High spec PC builder */
public class HighComputerBuilder implements Builder {

    private Computer computer = new Computer();

    @Override
    public void buildCpu(a) {
        computer.setCpu("The high-end CPU");
    }

    @Override
    public void buildMainBoard(a) {
        computer.setMainboard("High quality motherboard");
    }

    @Override
    public void buildDisk(a) {
        computer.setDisk("High spec disk");
    }

    @Override
    public void buildPower(a) {
        computer.setPower("High power supply");
    }

    @Override
    public void buildMemory(a) {
        computer.setMemory("High memory");
    }

    @Override
    public Computer createComputer(a) {
        return computer;// Returns the computer object}}Copy the code
/ * * *@Auther: csp1999
 * @Date: 2020/11/08 / they *@Description: Concrete builder class B: low power PC builder */
public class LowComputerBuilder implements Builder {

    private Computer computer = new Computer();

    @Override
    public void buildCpu(a) {
        computer.setCpu("With low CPU");
    }

    @Override
    public void buildMainBoard(a) {
        computer.setMainboard("Low motherboard");
    }

    @Override
    public void buildDisk(a) {
        computer.setDisk("Low disk");
    }

    @Override
    public void buildPower(a) {
        computer.setPower("Low power supply");
    }

    @Override
    public void buildMemory(a) {
        computer.setMemory("Low memory");
    }

    @Override
    public Computer createComputer(a) {
        return computer;// Returns the computer object}}Copy the code

Finally, the commander **Director ** controls the production process:

/ * * *@Auther: csp1999
 * @Date: 2020/11/08 / he *@Description: The Director class: controls the assembly process, hands the requirements to the builder, who creates the objects * * Decouples the product from the creation process, creates different products using the same creation process, and controls the production process * * The Director directs the assembly process, and the Builder handles the details */
public class Director {

    public Computer create(Builder builder){
        builder.buildCpu();
        builder.buildDisk();
        builder.buildMainBoard();
        builder.buildMemory();
        builder.buildPower();

        returnbuilder.createComputer(); }}Copy the code

When we’re done, let’s test:

@Test
public void testBuilder(a){
    Director director = new Director();// Declare the commander
    // The conductor constructs the low configuration computer
    Computer low_computer = director.create(new LowComputerBuilder());
    // The conductor directs the construction of the high configuration computer
    Computer high_computer = director.create(new HighComputerBuilder());
    System.out.println(low_computer);
    System.out.println(high_computer);
}
Copy the code

Output result:

Computer{cpu='with low CPU', memory='Low memory', mainboard='Low profile motherboard', disk='Low disk', power='Low power supply'}
Computer{cpu='the high-end CPU', memory='High memory', mainboard='High quality motherboard', disk='High spec disk', power='High power supply'}
Copy the code

Builder mode case completed!

4.3 summary

  • Builder mode benefits

    • The client does not have to know the details of the product’s internal composition, decoupling the product itself from the product creation process
    • Each concrete builder is relatively independent of the other concrete builders and has more fine-grained control over the product creation process
    • Adding a new concrete builder does not need to modify the original library code, in accordance with the open closed principle
    • Builder mode is used in conjunction with chained programming for more beautiful code
  • Disadvantages of builder mode

    • The builder pattern creates products that have a lot in common and are not recommended if the products are very different
  • Application in JDK

    • TCP transport protocol API generated by protobuf, StringBuilder in Java (not exactly identical, same idea)
  • Builder pattern vs. Abstract Factory pattern:

    • The Builder pattern returns an assembled complete product, and the Abstract Factory pattern returns a series of related products that are located in different product hierarchy structures and constitute a product family
    • The Builder pattern is to spread out the creation of objects, with each abstract method responsible for part of it. Abstract factories are each method responsible for a product family.
    • All the constructor mode functions add up to produce an object. Abstract factory a function generates an object.

The difference between the abstract Factory model and the Builder model is still a little confusing. Here’s a quick example:

  • For example, Huawei mobile phone manufacturing, Huawei Brilliance series and Huawei Nova series products are produced by FactoryProducer. FactoryProducer has its own IFactory, which is responsible for the production of Huawei mobile phone functions (interfaces/methods in abstract classes). This abstract factory has two sub-factories which are responsible for the actual production of honor mobile phones (Honor product family) and Huawei Nova mobile phones (Nova product family). The products produced from these two sub-factories are Honor mobile phones (Honor product family) and Huawei Nova mobile phones (Nova product family). This process belongs to the abstract factory pattern;
  • In the same example above, the process of cobbling together A Huawei phone from the production lines of two sub-factories is calledBuilder modelFor example, the head of the current production line (Director commanders) Instruct the production line to produce Nova 4 model of Nova series mobile phone (director.create(new Nova4());) the specific process of building and assembling this type of mobile phone is encapsulated innew Nova4()If the commander temporarily needs an assembly line to assemble a Nova 5 phone product, then onlydirector.create(new Nova5());Can.

In order to compare the differences between the factory mode and the Builder mode, here is a link to learn the factory Mode, a common design pattern for beginners in Java.

Later I will update other design mode blog posts, if the article is helpful to you, hope to click on the likes/favorites/follow! O ~ O (studying studying)