Definition: The Builder design pattern belongs to the creation design pattern. Separating the construction of a complex object from its representation allows the same construction process to create different representations.

Builder’s structure drawing:

In Builder mode there are the following characters:

  • Product: indicates the Product category
  • Builder: Build the Builder class from which to build the product class
The demo & code
public class Computer {
    private String cpu;
    private String ram;
    private String mainboard;
    private Computer(Builder builder) {
        setCpu(builder.cpu);
        setRam(builder.ram);
        setMainboard(builder.mainboard);
    }
    public String getCpu() {
        return cpu;
    }
    public void setCpu(String cpu) {
        this.cpu = cpu;
    }
    public String getRam() {
        return ram;
    }
    public void setRam(String ram) {
        this.ram = ram;
    }
    public String getMainboard() {
        return mainboard;
    }
    public void setMainboard(String mainboard) {
        this.mainboard = mainboard;
    }
    @Override
    public String toString() {
        return(cpu! =null? ("cpu:" + cpu):"") + (ram! =null? (" ,ram" + ram):"") + (mainboard! =null? (" ,mainboard" + mainboard):"");
    }

    static class Builder {
        private String cpu;
        private String ram;
        private String mainboard;
        public Builder cpu(String val) {
            cpu = val;
            return this;
        }
        public Builder ram(String val) {
            ram = val;
            return this;
        }
        public Builder mainboard(String val) {
            mainboard = val;
            return this;
        }
        public Computer build() {
            returnnew Computer(this); }}}Copy the code
Usage scenarios
  • When algorithms that create complex objects should be independent of the components of the object and how they are assembled.
  • Consider using a builder when you encounter multiple constructor parameters. Static factories and constructors have a common limitation: neither scale well to a large number of optional parameters.
advantages
  • Using the Builder pattern enables clients to avoid having to know the internal composition details of the product.
  • Specific builders are independent of each other and easy to scale.
  • Since the specific builder is independent, it is possible to refine the construction process without any impact on other modules.
disadvantages
  • Generate redundant Build objects

Code has been uploaded to Github