[design mode 4] builder mode

Posted by Ixplodestuff8 on Mon, 17 Jan 2022 10:24:30 +0100

introduce

  1. Builder Pattern, also known as Builder Pattern, is an object construction pattern. It can abstract the construction process of complex objects (abstract categories), so that different implementation methods of this abstract process can construct objects with different representations (attributes).
  2. Builder mode is to create a complex object step by step. It allows users to build complex objects only by specifying their types and contents. Users do not need to know the specific internal construction details.
  3. The Builder pattern uses multiple simple objects to build a complex object step by step. This type of design pattern is a creation pattern, which provides the best way to create objects. A Builder class will construct the final object step by step. The Builder class is independent of other objects.

The four roles of the builder model

The four roles of the builder model

  1. Product role: a specific product object.
  2. Builder (Abstract builder): create an interface / abstract class specified by each part of a Product object.
  3. ConcreteBuilder: implement interfaces, build and assemble various components.
  4. Director: build an object that uses the Builder interface. It is mainly used to create a complex object. It has two main functions: one is to isolate the production process of customers and objects; the other is to control the production process of product objects.

Builder pattern UML class diagram

Life example

For example, different characters in the game have different gender, personality, ability, face shape, body shape, clothing, hairstyle and other characteristics; There are also a variety of steering wheel, engine, frame, tires and other components in cars; The sender, recipient, subject, content and attachment of each e-mail are also different. All the above products are composed of multiple parts. Each part can be selected flexibly, but its creation steps are similar. The creation of this kind of product cannot be described by the factory mode described above. Only the builder mode can well describe the creation of this kind of product.

Notes and details of builder mode

advantage:

  1. The client (user program) does not need to know the details of the internal composition of the product, and decouples the product itself from the product creation process, so that the same creation process can create different product objects.
  2. Each specific builder is relatively independent and has nothing to do with other specific builders. Therefore, it is convenient to replace or add new specific builders. Users can get different product objects by using different specific builders.
  3. You can more finely control the product creation process. The creation steps of complex products are decomposed into different methods, which makes the creation process clearer and easier to use programs to control the creation process. The builder can gradually refine the creation process without any impact on other modules, so as to control the detail risk.
  4. 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 expansion is convenient and conforms to the "opening and closing principle".
  5. Good encapsulation, separation of construction and representation; Good expansibility, each specific builder is independent of each other, which is conducive to the decoupling of the system.

Disadvantages:

  1. The products created by the builder mode generally have more in common and their components are similar. If there are great differences between products, the builder mode is not suitable for use, so its scope of use is limited.

  2. If the internal changes of the product are complex, it may lead to the need to define many specific builder classes to implement such changes, resulting in a huge system. Therefore, in this case, it is necessary to consider whether to select the builder mode.

Abstract factory pattern VS builder pattern

  1. Abstract factory mode realizes the creation of product families. A product family is a series of products: product combinations with different classification dimensions. Adopting abstract factory mode does not need to care about the construction process, but only about what products are produced by what factory.

  2. The builder model requires the product to be built according to the specified blueprint. Its main purpose is to produce a new product by assembling spare parts.

  3. The two can be used in combination.

Sample code

1. product house

/**
 * Product -- house
 */
public class House {

    //foundation
    private String foundation;

    //wall 
    private String wall;

    //roof
    private String roofed;

    public String getFoundation() {
        return foundation;
    }

    public void setFoundation(String foundation) {
        this.foundation = foundation;
    }

    public String getWall() {
        return wall;
    }

    public void setWall(String wall) {
        this.wall = wall;
    }

    public String getRoofed() {
        return roofed;
    }

    public void setRoofed(String roofed) {
        this.roofed = roofed;
    }
}

2. Abstract Builder: it includes the abstract method of creating each sub part of the product.

import design.builder.product.House;

//Abstract class for building a house
public abstract class HouseBuilder {

    //Built products
    protected House house = new House();

    //Write the construction process and abstract method
    public abstract void buildFoundation();
    public abstract void buildWalls();
    public abstract void roofed();

    //Build a house and return the product (house)
    public House buildHouse() {
        return house;
    }
}

3. Concrete builder, inheriting Abstract builder

public class CommonHouseBuilder  extends HouseBuilder{
    @Override
    public void buildFoundation() {
        house.setFoundation("Foundation 1 m depth");
        System.out.println("Ordinary house foundation");
    }

    @Override
    public void buildWalls() {
        house.setWall("Wall 1 m thick");
        System.out.println("Walls of ordinary houses");
    }

    @Override
    public void roofed() {
        house.setRoofed("Ceiling triangle");
        System.out.println("The ceiling of an ordinary house");
    }
}

public class HighHouseBuilder extends HouseBuilder{
    @Override
    public void buildFoundation() {
        house.setFoundation("Foundation 1 Km");
        System.out.println("The foundation of a skyscraper");
    }

    @Override
    public void buildWalls() {
        house.setWall("Wall glass");
        System.out.println("Walls of skyscrapers--8KM");
    }

    @Override
    public void roofed() {
        house.setRoofed("Canopy Pentagram");
        System.out.println("The roof of a skyscraper");
    }
}

4. Commander: call the method in the builder to complete the creation of complex objects.

import design.builder.build.HouseBuilder;
import design.builder.product.House;

//The house construction commander calls the component construction and assembly methods in the builder object to complete the creation of complex objects,
//Information that does not involve specific products in the commander
public class HouseDirector {


    HouseBuilder houseBuilder = null;

    //Constructor passed into houseBuilder
    public HouseDirector(HouseBuilder houseBuilder) {
        this.houseBuilder = houseBuilder;
    }

    //How to deal with the process of building a house and leave it to the commander
    public House constructHouse() {
        houseBuilder.buildFoundation();
        houseBuilder.buildWalls();
        houseBuilder.roofed();
        return houseBuilder.buildHouse();
    }
}

5. Call the client

import design.builder.build.CommonHouseBuilder;
import design.builder.build.HighHouseBuilder;
import design.builder.product.House;

//Client call
public class Client {

    public static void main(String[] args) {

        //Build an ordinary house
        CommonHouseBuilder commonHouse = new CommonHouseBuilder();
        //The commander ready to create the house
        HouseDirector houseDirector = new HouseDirector(commonHouse);

        //Finish building a house and return to the product (ordinary house)
        House house = houseDirector.constructHouse();
        System.out.println(house.toString());

        //System.out.println("output process");

        System.out.println("--------------------------");
        //Build a tall building
        HighHouseBuilder highBuilding = new HighHouseBuilder();
        //Reset builder
        HouseDirector houseDirector2 = new HouseDirector(highBuilding);
        //Finish building the house and return to the product (high-rise building)
        House house1 = houseDirector2.constructHouse();
        System.out.println(house1.toString());

    }
}

JDK source code application StringBuilder

Role analysis of builder pattern in source code
The Appendable interface defines multiple append methods (abstract methods), that is, Appendable is the abstract builder and defines abstract methods
The AbstractStringBuilder implements the Appendable interface method. The AbstractStringBuilder here is already the builder, but it cannot be instantiated.
 StringBuilder acts as both a commander and a specific builder. The implementation of the construction method is completed by AbstractStringBuilder, which inherits AbstractStringBuilder

Topics: Java