“This is the fifth day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

Builder model

1. What is the Builder model

  1. Builder Pattern, also called generator 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 different performance (attributes) of the object, such a design pattern is called the builder pattern.
  2. It takes a complex object and breaks it down into simple objects and builds it step by step. It separates change from immutability, that is, the components of a product are constant, but each part can be selected flexibly.

2. Builder model understanding

2.1 Main Structure

  1. Product: It is a complex object with multiple components, i.e. a concrete Product.
  2. Abstract Builder: This is an interface/abstract class that contains abstract methods for creating the various child parts of a product, usually including a method called getResult() that returns a complex product.
  3. Concrete Builder: to realize the Builder interface and complete the Concrete creation method of each part of complex products.
  4. Director: Build an object that uses the Builder interface. It is primarily used to create a complex object. It mainly has two functions, one is: isolated the production process of the customer and the object, the other is: responsible for controlling the production process of the product object.

2.2 Schematic class diagram

3. Code

3.1 products

// Product public class House {private String baise; private String wall; private String roofed; }Copy the code

3.2 Abstract Builder Builder

Public abstract class HouseBuilder {protected House House = new House(); Public abstract void buildBasic(); public abstract void buildWalls(); public abstract void roofed(); Public House buildHouse() {return House; }}Copy the code

3.3 Specific builder (there can be multiple depending on the specific implementation)

Public class HighBuilding extends HouseBuilder {@override public void buildBasic() {system.out.println (" HighBuilding extends HouseBuilder {@override public void buildBasic() {system.out.println ( "); } @override public void buildWalls() {system.out.println (" buildWalls 20cm "); } @override public void roofed() {system.out.println (" roofed "); }}Copy the code

3.4 commanders

public class HouseDirector { HouseBuilder houseBuilder = null; HouseBuilder public HouseDirector(houseBuilder) {this.houseBuilder = houseBuilder; } public void setHouseBuilder(houseBuilder) {this.houseBuilder = houseBuilder; Public House constructHouse() {houseBuilder.buildbasic (); public House constructHouse() {houseBuilder.buildbasic (); houseBuilder.buildWalls(); houseBuilder.roofed(); return houseBuilder.buildHouse(); }}Copy the code

3.5 Call Method

Public static void main(String[] args) {HighBuilding HighBuilding = new HighBuilding(); HouseDirector HouseDirector = new HouseDirector(highBuilding); / / finish building a house, return the product (tall) houseDirector. ConstructHouse (); }Copy the code

4. Application scenarios

Builder patterns usually applies to create complex object, when you need to create products with complex creation process, you can extract the creation process, and then to a concrete implementation class custom creation process, makes the same create behavior can produce different products, separation of creation and says, greatly increases the flexibility to create products.

The Builder pattern applies to the following scenarios:

  • Same method, different order of execution, produce different results.
  • Multiple parts, or parts, can be assembled into an object but produce different results.
  • The product class is very complex, or different calls in the product class have different effects.
  • Initializing an object is extremely complex with many parameters, many of which have default values.

5. Differences with factory mode

Abstract factory pattern implements the creation of a product family. A product family is a series of products: a combination of products with different classification dimensions. The abstract factory pattern does not care about the construction process, but only what products are produced by what factories. The builder model focuses on the build process, building a particular product in a particular order. The factory model focuses on creating objects, not process, whereas the builder focuses on building processes, creating different products

6. Pay attention to detail

  1. The Builder pattern, in which customers do not have to know the details of the product’s internal composition, decouples the product itself from the product creation process so that the same creation process can create different product objects

  2. The builder, as well as the director, can be the same class or a different class

  3. Each concrete builder is relatively independent of other concrete builders, so it is easy to replace concrete builders or add new concrete builders, and users can use different concrete builders to get different product objects

  4. The product creation process can be more finely controlled. Breaking down the creation steps of complex products into different methods makes the creation process clearer and easier to control programmatically

  5. Adding a new concrete builder does not need to modify the code of the original class library. The commander class is programmed for the abstract builder class, and the system is easy to expand and conforms to the “open and close principle”.

  6. The products created by the Builder mode generally have more in common and their components are similar. If the differences between the products are large, the builder mode is not suitable for use, so its application scope is limited to a certain extent.

7. Application cases

1.StringBuilder

public final class StringBuilder extends AbstractStringBuilder implements java.io.Serializable, CharSequence { @Override public StringBuilder append(String str) { super.append(str); return this; }}Copy the code

Look up at super.append(STR);

abstract class AbstractStringBuilder implements Appendable, CharSequence { public AbstractStringBuilder append(String str) { if (str == null) return appendNull(); int len = str.length(); ensureCapacityInternal(count + len); str.getChars(0, len, value, count); count += len; return this; }}Copy the code

Open the Appendable interface

So Appendable is an abstract builder,AbstractStringBuilder is a construction method that implements Appendable, which is also a builder, but because it’s an abstract class, it can’t be instantiated, So its subclass, StringBuilder, is the builder, String is the commodity, and StringBuilder is the conductor.

2. When we annotated @Builder with Lombok, we were automatically given the source code for the Builder class

@Builder
@Data
public class Student {
   private String name;
   private String addr;
   private Double height;
}
Copy the code

The generated code omits the constructor toString method

public class Student { private String name; private String addr; private Double height; public static Student.StudentBuilder builder() { return new Student.StudentBuilder(); } public static class StudentBuilder { private String name; private String addr; private Double height; StudentBuilder() { } public Student.StudentBuilder name(final String name) { this.name = name; return this; } public Student.StudentBuilder addr(final String addr) { this.addr = addr; return this; } public Student.StudentBuilder height(final Double height) { this.height = height; return this; } public Student build() { return new Student(this.name, this.addr, this.height); } public String toString() { return "Student.StudentBuilder(name=" + this.name + ", addr=" + this.addr + ", height=" + this.height + ")"; }}Copy the code

Student is the product, StudentBuilder is the concrete builder and director.