Fork me on GitHub

代理模式五:构建者模式

简介

将一个复杂对象的构建与其表示分离,使得同样的构建过程可以创建不同的表示

使用场景

当创建一个对象时,参数超过4个且参数可选择,可以考虑使用

代码

  • 实现类
public class Computer implements Serializable {
    private final String cpu; //必须
    private final String ram; //必须
    private final String usbCount; //可选
    private final String keyboard; //可选
    private final String display; //可选


    public Computer(Builder computer) {
        this.cpu = computer.cpu;
        this.ram = computer.ram;
        this.usbCount = computer.usbCount;
        this.keyboard = computer.keyboard;
        this.display = computer.display;
    }

    public static class Builder{
        private  String cpu; //必须
        private  String ram; //必须
        private  String usbCount; //可选
        private  String keyboard; //可选
        private  String display; //可选

        public Builder(String cpu, String ram) {
            this.cpu = cpu;
            this.ram = ram;
        }



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



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


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

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

    @Override
    public String toString() {
        return "Computer{" +
                "cpu='" + cpu + '\'' +
                ", ram='" + ram + '\'' +
                ", usbCount='" + usbCount + '\'' +
                ", keyboard='" + keyboard + '\'' +
                ", display='" + display + '\'' +
                '}';
    }
}
  • 测试类
 public class BuilderTest {

    public static void main(String[] args) {
        Computer build = new Computer.Builder("因特尔", "三星")
                .setUsbCount("2")
                .build();
        System.out.println(build);
    }

}

Gitee地址

https://gitee.com/zhuayng/foundation-study.git

参考

https://blog.csdn.net/ShuSheng0007/article/details/86619675

posted @ 2021-08-19 18:50  晨度  阅读(23)  评论(0编辑  收藏  举报