构造函数build模式

public class Student {
    private String name;
    private int stuNum;
    private int age;
    private int classNum;
    private int height;
    private int weight;

    public Student(Builder builder) {
        this.name = builder.name;
        this.stuNum = builder.stuNum;
        this.age = builder.age;
        this.classNum = builder.classNum;
        this.height = builder.height;
        this.weight = builder.weight;
    }

    public static class Builder{
        //必有的
        private String name;
        private int stuNum;
        //可选的
        private int age;
        private int classNum;
        private int height;
        private int weight;

        public Builder(String name, int stuNum) {
            this.name = name;
            this.stuNum = stuNum;
        }
        public Builder age(int val){
            age = val;
            return this;  //返回该完整实例,方便后面的函数继续设置属性值
        }
        public Builder classNum(int val){
            classNum = val;
            return this;
        }
        public Builder height(int val){
            height = val;
            return this;
        }
        public Builder weight(int val){
            weight = val;
            return this;
        }

        //最终build()函数调用类的构造函数,并将builder传入
        public Student build(){
            return new Student(this);
        }
    }
}

posted @ 2019-05-15 11:05  ytsee  阅读(72)  评论(0)    收藏  举报