Design mode - builder mode

preface

This article refers to dark horse's design pattern handout and c language Chinese network tutorial C language Chinese network tutorial , rookie tutorial: Rookie tutorial . There are also some of their own understanding. It is still difficult to summarize a set of concepts by themselves. Dark horse video: Dark horse design pattern . The builder mode is introduced below, which is also common in projects.

Tip: the following is the main content of this article. The following cases can be used for reference


1. General

In life, our common cars, computers, etc. are obtained by the combination of parts one by one. We want to get these by ourselves. We don't need to assemble them by ourselves, but the manufacturer will help us assemble them. The assembly of these products is composed of many parts, and the assembly process is very flexible. The parts are not required to be the same, but can be of different brands. In this way, the use of prototype model is obviously not suitable, and the use of factory mode is not suitable. Here is a new way: Builder mode

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. In this pattern, we define a builder, which helps us create the desired object.



2. Advantages and disadvantages

1. Advantages

  • It separates the construction of components (in the charge of Builder) and assembly (in the charge of Director). Consistent with the principle of single responsibility
  • Due to the decoupling of construction and assembly. Different builders and the same assembly can also make different objects; With the same builder, different assembly sequences can also make different objects. That is to realize the decoupling of construction algorithm and assembly algorithm, and realize better reuse.
  • The builder pattern can separate the component from its assembly process and create a complex object step by step. Users only need to specify the type of complex object to get the object without knowing its internal specific construction details. It realizes the decoupling between users and product creation process
  • Conducive to expansion, the creator is independent



2. Disadvantages

  • The maintenance cost is high. If the internal changes are complex, many construction classes are required
  • Products must have something in common and the scope must be limited



3. Structure

The Builder pattern includes the following roles:

  • Abstract Builder class: this interface specifies the creation of those parts of complex objects, and does not involve the creation of specific component objects.
  • ConcreteBuilder: it implements the Builder interface and completes the specific creation method of each component of complex products. After the construction process is completed, provide an example of the product.
  • Product: complex object to be created.
  • Director: call the specific builder to create each part of the complex object. The director does not involve the information of the specific product, but is only responsible for ensuring that each part of the object is created completely or in a certain order.



4. Cases

The production of bicycle is a complex process, which includes the production of frame, seat and other components. The frame is made of carbon fiber, aluminum alloy and other materials, and the seat is made of rubber, leather and other materials. For the production of bicycles, the builder mode can be used.

Implementation code:

1. Bicycle class to be generated finally

@Data
public class Bike {
    private String frame;
    private String seat;
}

2. Abstract builder class, which defines the method of creating frame and seat, and allows the corresponding creator to create

public abstract class Builder {
	//Provide vehicles that are not loaded
    protected Bike mBike = new Bike();
    //Create frame
    public abstract void buildFrame();
    //Create seat
    public abstract void buildSeat();
    //Bicycle parts gongzuao
    public abstract Bike createBike();
}

3. Moby bike creation class (specific builder)

public class MobikeBuilder extends Builder{
    @Override
    public void buildFrame() {
        mBike.setFrame("Aluminum alloy frame");
    }

    @Override
    public void buildSeat() {
        mBike.setSeat("Leather seat");
    }

    @Override
    public Bike createBike() {
        return mBike;
    }
}

4. ofo bicycle creation class (specific builder)

public class OfoBuilder extends Builder {

    @Override
    public void buildFrame() {
        mBike.setFrame("Carbon fiber frame");
    }

    @Override
    public void buildSeat() {
        mBike.setSeat("Rubber seat");
    }

    @Override
    public Bike createBike() {
        return mBike;
    }
}

5. Director, the conductor class, is used to specify which kind of bicycle to create

public class Director {
    private Builder builder;

    public Director(Builder builder) {
        this.builder = builder;
    }

    public Bike construct() {
        builder.buildFrame();
        builder.buildSeat();
        return builder.createBike();
    }
}

6. Client class (test class)

public class Client {
    public static void main(String[] args) {
        showBike(new OfoBuilder());
        //Carbon fiber frame
        //Rubber seat
        showBike(new MobikeBuilder());
        //Aluminum alloy frame
        //Leather seat
    }
    private static void showBike(Builder builder) {
        //Create a commander
        Director director = new Director(builder);
        //The commander creates a bike
        Bike bike = director.construct();
        //Frame
        System.out.println(bike.getFrame());
        //Car seat
        System.out.println(bike.getSeat());
    }
}


In the above code, the commander can be written in the abstract builder. This method can be used in conjunction with the responsibility chain pattern. For example, in the construct method of this class, a responsibility chain of single chain table can be created. Many builder modes are also used in Mybatis. For example, the cache processing in Mybatis uses the builder + responsibility chain mode. This mode is very clear to use, the structure of classes is very clear, and what each class needs to do is clear at a glance.

// Abstract builder class
public abstract class Builder {

    protected Bike mBike = new Bike();

    public abstract void buildFrame();
    public abstract void buildSeat();
    public abstract Bike createBike();
    
    public Bike construct() {
        this.buildFrame();
        this.BuildSeat();
        return this.createBike();
    }
}



5. Usage scenario

The Builder pattern creates complex objects. Each part of its product is often faced with drastic changes, but the algorithm that combines them is relatively stable, so it is usually used in the following occasions.

  • The created object is complex and consists of multiple components. Each component is facing complex changes, but the construction sequence between components is stable.
  • The algorithm of creating a complex object is independent of the components of the object and their assembly mode, that is, the construction process and final representation of the product are independent.

For an example, see the source code of Mybatis cache mentioned above



6. Mode extension

When writing a project, it is usually used in a class. Specifically, this article discusses in detail why to use the builder pattern and how to use it. Use creator mode to create objects

However, one disadvantage of this kind of use is that when you want to use reflection to assign values, you will not find the corresponding method to assign values, because there are no get and set methods in such a class, and there is no way to change the created objects, which realizes the immutability of the class to some extent. But don't use this method when a class needs to be created and often needs to be changed.





If there is any error, please point it out!!!

Keywords: Design Pattern

Added by diesel_heart on Sun, 06 Feb 2022 07:35:55 +0200