当前位置:网站首页>Thoroughly understand the builder mode (builder)

Thoroughly understand the builder mode (builder)

2022-06-22 14:41:00 happysnaker

The article has been included in my warehouse :Java Share your study notes with free books

Design intent

To separate the construction of a complex object from its representation , So that objects can be created through different representations .

For example, a maze may have walls 、 Rooms and doors , And the quantity is not counted . The labyrinth may consist of only one wall , It may also consist of two walls , It may also be by 2 A room with a door … If the labyrinth is produced by heavy load , The amount of code is hard to count 、 Incomparably large .

Having a large number of components for an object ( A maze can have many walls or rooms or doors ), And the use of its components by constructing this object is uncertain ( Working with walls 、 room 、 The number of doors is uncertain ), Want fine-grained control over the build process , At this point, the builder mode can be used to solve the problem .

The intention of the builder pattern is to construct objects , So it belongs to the creation mode .

Applicable scenario

  • During construction , The constructed objects have different representations .
  • Some basic components don't change , And its combination often changes .
  • The internal properties of the objects that need to be generated depend on each other .

Design

Assign a builder to the commander in chief , The commander in chief designs how to build , Actually built by the builder , Finally, the builder hands over the product to the commander in chief , The user completes the delivery from the commander in chief .

This process is very humanized , For example, our actual house decoration is the same , We asked some workers , Ask another worker leader to design and build ideas , Instruct these workers how to decorate , We only deal with the leaders of the workers next , The leader of the workers handed over the decorated house to us .

Code example

Consider the above maze problem :

// Define the maze class 
class Maze {
    
    public void setRoom(int x, int y, int roomId) {
    
        System.out.println(" stay [" + x + "," + y + "] A building numbered " + roomId + " Room ");
        // Keep relevant information 
    }

    public void setDoor(int Id1, int Id2) {
    
        System.out.println(" When the component number is " + Id1 + " And component number " + Id2 + " Build a door between ");
        // Keep relevant information 
    }

    public void setBarrier(int x, int y, int barrierId) {
    
        System.out.println(" stay [" + x + "," + y + "] A building numbered " + barrierId + " The obstacles ");
        // Keep relevant information 
    }
}

// Define the maze builder interface 
interface MazeBuilder {
    
    void buildRoom(int x, int y, int roomId);// Build a room 
    void buildDoor(int Id1, int Id2);// Building doors 
    void buildBarrier(int x, int y, int barrierId);// Build obstacles 
    Maze getMaze();// Get the end result 
}

// Maze building team A, The way each construction team builds is different 
class MazeBuilderA implements MazeBuilder {
    
    // The construction team will gradually improve the maze , And deliver to customer 
    private Maze maze = new Maze();


    @Override
    public void buildRoom(int x, int y, int roomId) {
    
        maze.setRoom(x, y, roomId);
    }

    @Override
    public void buildDoor(int Id1, int Id2) {
    
        maze.setDoor(Id1, Id2);
    }

    @Override
    public void buildBarrier(int x, int y, int barrierId) {
    
        maze.setBarrier(x, y, barrierId);
    }

    @Override
    public Maze getMaze() {
    
        return maze;
    }
}

// Maze director class 
class MazeDirecotr {
    
    MazeBuilder mazeBuilder;

    public MazeDirecotr(MazeBuilder mazeBuilder) {
    
        this.mazeBuilder = mazeBuilder;
    }

    // Hand over the work to the commander , The user only needs to wait for the building to complete the removal of the instance 
    public Maze getMaze() {
    
        // Specific design ideas are produced here 
        // Here we can construct a complex model step by step according to our ideas 
        // For example, here I want to build two rooms and a door in the middle 
        mazeBuilder.buildRoom(0, 0, 0);
        mazeBuilder.buildRoom(0, 1, 1);
        mazeBuilder.buildDoor(0, 1);

        // The actual work is built by the workers 
        // The commander in chief obtains the final product from the workers , The chief commander shall complete the handover with the user 
        return mazeBuilder.getMaze();
    }
}

// Test class 
public class Test {
    
    public static void main(String[] args) {
    
        // Ask the workers to 
        MazeBuilder mazeBuilder = new MazeBuilderA();

        // Please command , And hand over the workers to their command 
        MazeDirecotr mazeDirecotr = new MazeDirecotr(mazeBuilder);

        // Finally, complete the product delivery with the commander in chief 
        Maze maze = mazeDirecotr.getMaze();
    }
}
// Output 
/*  stay [0,0] A building numbered 0 Room   stay [0,1] A building numbered 1 Room   When the component number is 0 And component number 1 Build a door between  */

Through the builder model , We no longer need to overload a large number of functions . By designing the director class, we can generate the desired objects step by step , The creation process can be more finely controlled . In development , The director class is defined by the user , An optimization technique is to use chained programming , We can define the builder interface as follows :

// Define the maze builder interface 
interface MazeBuilder {
    
    MazeBuilder buildRoom(int x, int y, int roomId);// Build a room 
    MazeBuilder buildDoor(int Id1, int Id2);// Building doors 
    MazeBuilder buildBarrier(int x, int y, int barrierId);// Build obstacles 
    Maze getMaze();// Get the end result 
}

Then we can write code in the director class like this :

                                         mazeBuilder.buildRoom(0, 0, 0).buildRoom(0,1,1).buildDoor(0, 1);

Summary of advantages and disadvantages

advantage :

1、 Independence of builders , Interface mode is adopted , Easy to expand .

2、 Easy to control detail risk .

3、 Decouple design from use , Easy to expand and maintain .

shortcoming :

1、 Products must have something in common , The scope is limited .

2、 If the internal changes are complicated , There will be a lot of construction classes .

** matters needing attention :** The difference from the factory model is : Builder mode pays more attention to the order of parts assembly .

原网站

版权声明
本文为[happysnaker]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206221314157968.html