Builder pattern

As the name implies, create objects like building a house by configuring different parameters, such as floor color, ceiling color, wall color, etc. Finally make the final design drawing for construction

The advantages and disadvantages

advantages

1) Reduce the code coupling degree. In builder mode, the client doesn’t need to know how the product is implemented internally, we just need to get the object of the product. Moreover, the director and the builder are used to separate the assembly process from the component construction process, which has flexible scalability.

2) Excellent scalability. Specific builders are independent of each other, convenient expansion, in line with the principle of open and closed.

disadvantages

1) Limited scope of use. The components of the builder mode products are basically the same, and if the products are very different, the Builder mode will not work

Code design

Design a house, determine the layout of the house, decoration and footprint of each room to determine the final design

public class HouseBuild { private String door; private String room; private String toilet; public HouseBuild(Builder builder) { this.door=builder.door; this.room=builder.room; this.toilet=builder.toilet; } public String build(){return "+room +", "+toilet +", "+door; } static class Builder { private String door; private String room; private String toilet; public Builder door(String door) { this.door = door; return this; } public Builder room(String room) { this.room = room; return this; } public Builder toilet(String toilet) { this.toilet = toilet; return this; } public HouseBuild build() { return new HouseBuild(this); }}}Copy the code

use

Public static void main(String[] args) {HouseBuild HouseBuild =new housebuild.builder ().room("25 flat house ").door(" red house ") .toilet("5 flat toilet ").build(); System.out.println(houseBuild.build()); } output "design new successfully, the room is :25 square house, the bathroom is :5 square toilet, the door is: red door"Copy the code

After the speech

The Builder mode can set some default values when validating individual configuration items; For example, the default door is black and the bathroom is 10 equal. In this way, when some new configuration items are added, for example, the house type is increased by 50 square meters, then other design schemes can be made based on this 50 square meters; For the previous design, the new 50-square design is blank;