JS Bin

建造者模式总结与代码模板

/**
 * @author 左五六
 * @Date 2020/9/9 10:07
 */


/**
 * 建造者模式(重点)
 * 1、静态内部类,含必选参数的构造器
 * 2、静态内部类Builder包含所有的原实例的所有属性
 * 3、set方法返回Builder实例
 * 4、原实例类里面包含有一个私有的构造方法传进来的是builder实例
 * 5、最后在静态Builder里面提供一个build方法,return new 实例(this)
 *
 * */

public class Computer {

    private String cpu;//1,表示必须
    private String ram;//1
    private int usbCount;//2
    private String keyBoard;//2
    private String display;//2

    //提供了一个私有的构造方法,供本类里面调用
    private Computer(Builder builder){
        this.cpu = builder.cpu;
        this.display = builder.display;
        this.keyBoard = builder.keyBoard;
        this.ram = builder.ram;
        this.usbCount = builder.usbCount;
    }

    public static class Builder{
        private String cpu;//1,表示必须
        private String ram;//1
        private int usbCount;//2
        private String keyBoard;//2
        private String display;//2

        //必选参数通过builder的构造函数来指定
        public Builder(String cpu,String ram){
            this.cpu = cpu;
            this.ram = ram;
        }

        public Builder setUsbCount(int 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;
        }

        //提供build方法返回computer实例
        public Computer build(){
            return new Computer(this);
        }

    }

}

  参考:https://zhuanlan.zhihu.com/p/58093669

posted @ 2020-09-09 10:20  左五六  阅读(165)  评论(0编辑  收藏  举报