concept

Create a complex object step by step. The separation of parts and assembly process makes the construction process and parts can be expanded freely, and the construction process of objects can be more finely controlled. The disadvantage is that redundant Builder objects are generated.

Usage scenarios

  • The same method (multiple parts) in different execution (assembly) sequences produces different results
  • Initializing an object with many and complex parameters (with default values)
  • Usually used as a builder for configuration classes to avoid excessive setter methods.

implementation

  • Abstract Product and concrete Product classes
  • Abstract Builder and concrete Builder classes
  • The Director unified assembly process, used to separate the construction of an object from its representation, is typically omitted from development and lets the Builder form chain calls (each setter returns the Builder itself this) to simplify the structure.
public abstract class Product{
    protected String A;
    protected String B;

    public void setA(String a){
        A = a;
    }

    public void setB(String b){
        B = a;
    }
}

public class ProductA extends Product{
    //...
}

public abstract class Builder {
    public abstract void buildA(String a);
    public abstract void buildB(String b);
    public abstract Product create(); 
}

public class ABuilder extends Builder{
    private Product product = new ProductA();

    public void buildA(String a){
        product.setA(a);
    }
    public void buildB(String b){
        product.setB(b);
    }
    public Product create() {return product;
    }
}

public class Director {
    Builder builder = null;
    public Director(Builder builder){
        this.builder = builder;
    }
    public void construct(String a, String b){
        builder.buildA(a);
        builder.buildB(b);
    }
}

public class Test{
    public static void main(String[] args){
        Builder builder = new Builder();
        Director director = new Director(builder);
        director.construct("a"."b"); Product p = builder.create(); }}Copy the code