4) Builder Pattern

发布时间 2023-06-06 13:27:42作者: zno2

类别:

 Creational pattern

问题:

 构造函数入参超长易变

方案:

 

示例:

public class BuilderPatternDemo {
    public static void main(String[] args) {
        Car.Builder builder = new Car.Builder("Benz");
        Car car = builder.build();
        System.out.println(car);
        builder = new Car.Builder("Ford").type("Pickup").color("Red");
        car = builder.build();
        System.out.println(car);
    }

}

class Car {
    private String brand;
    private String type;
    private String color;

    public static class Builder {
        // 必填
        private String brand;
        // 选填
        private String type = "SUV";
        private String color = "black";

        public Builder(String brand) {
            this.brand = brand;
        }

        public Builder type(String type) {
            this.type = type;
            return this;
        }

        public Builder color(String color) {
            this.color = color;
            return this;
        }

        public Car build() {
            return new Car(this);
        }
    }

    /**
     * Builder 模式 不提供构造器
     */
    private Car(Car.Builder builder) {
        this.brand = builder.brand;
        this.type = builder.type;
        this.color = builder.color;
    }

    @Override
    public String toString() {
        return "Car [brand=" + brand + ", type=" + type + ", color=" + color + "]";
    }

}

 

应用:

 

不足:(

 

优化:)