建造者模式

2018-10-30  本文已影响0人  要学的东西太多了

分具体产品类,建造者类,导演类,常见的是客户端扮演导演类。由建造者来构建具体产品类的内部表象以及遵循怎样的约束条件,导演类来决定构建哪些部分和怎么构建,最后由建造者返回具体产品类的对象。客户端只能通过Builder来获取对象,隐藏了具体产品类的构建过程,我们常见的各种Builder就是采用了这个模式。
示例:

public class Person {
    private String name;
    private String sex;
    private double height;
    private double wight;
    private String address;
    private String work;

    private Person(Builder builder) {
        this.name=builder.name;
        this.sex=builder.sex;
        this.height=builder.height;
        this.wight=builder.wight;
        this.address=builder.address;
        this.work=builder.work;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                ", height=" + height +
                ", wight=" + wight +
                ", address='" + address + '\'' +
                ", work='" + work + '\'' +
                '}';
    }
    public static class Builder{
        private String name;
        private String sex;
        private double height;
        private double wight;
        private String address;
        private String work;

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

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

        public Builder setHeight(double height) {
            this.height = height;
            return this;
        }

        public Builder setWight(double wight) {
            this.wight = wight;
            return this;
        }

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

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

        public Person build(){
            if(name==null){
                throw new RuntimeException("name不能为空");
            }
            return new Person(this);
        }
    }
}
上一篇 下一篇

猜你喜欢

热点阅读