directory

  • introduce
  • Usage scenarios
  • implementation

introduce

  1. The Builder pattern is a creation pattern that allows the user to create a complex object by fine-tuning the construction flow of the object step by step without knowing the internal structure.
  2. The Builder pattern enables the separation of the construction and representation of complex objects, and the same construction process can create different representations.

Usage scenarios

The Builder pattern is used to build complex objects, and it locks the built objects that generally have the following characteristics

  1. The same method, different execution sequence, produce different event results.
  2. Multiple parts, or parts, can be assembled into an object, but produce different results.
  3. When object initialization is particularly complex, such as having multiple parameters, or parameters with default values.

implementation

public class Computer {
    protected String mBoard;
    protected String mDisplay;
    protected String mCpu;
    protected String mGpu;
    protected String mOs;

    public void setBoard(String board) {
        mBoard = board;
    }

    public void setDisplay(String display) {
        mDisplay = display;
    }

    public void setCpu(String cpu) {
        mCpu = cpu;
    }

    public void setGpu(String gpu) {
        mGpu = gpu;
    }

    public void setOs(String os) {
        mOs = os;
    }

    public static class Builder {
        Computer computer;

        public Builder(a) {
            computer = new Computer();
        }

        public Builder board(String board) {
            computer.setBoard(board);
            return this;
        }

        public Builder display(String display) {
            computer.setDisplay(display);
            return this;
        }

        public Builder cpu(String cpu) {
            computer.setCpu(cpu);
            return this;
        }

        public Builder gpu(String gpu) {
            computer.setGpu(gpu);
            return this;
        }

        public Builder os(String os) {
            computer.setOs(os);
            return this;
        }

        public Computer build(a) {
            returncomputer; }}}Copy the code