java8 (spring3.x)對建立型模式下建造者模式(其實和java8沒多大關係)

icool_ali發表於2018-07-25

我們需要建立一個學生物件,屬性有name,number,class,sex,age,school等屬性,如果每一個屬性都可以為空,也就是說我們可以只用一個name,也可以用一個school,name,或者一個class,number,或者其他任意的賦值來建立一個學生物件,這時該怎麼構造?可以建立任意的建構函式

難道我們寫6個1個輸入的建構函式,15個2個輸入的建構函式.......嗎?這個時候就需要用到Builder模式了

 

public class Builder {

    static class Student{
        String name = null ;
        int number = -1 ;
        String sex = null ;
        int age = -1 ;
        String school = null ;

     //構建器,利用構建器作為引數來構建Student物件
        static class StudentBuilder{
            String name = null ;
            int number = -1 ;
            String sex = null ;
            int age = -1 ;
            String school = null ;
            public StudentBuilder setName(String name) {
                this.name = name;
                return  this ;
            }

            public StudentBuilder setNumber(int number) {
                this.number = number;
                return  this ;
            }

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

            public StudentBuilder setAge(int age) {
                this.age = age;
                return  this ;
            }

            public StudentBuilder setSchool(String school) {
                this.school = school;
                return  this ;
            }
            public Student build() {
                return new Student(this);
            }
        }

        public Student(StudentBuilder builder){
            this.age = builder.age;
            this.name = builder.name;
            this.number = builder.number;
            this.school = builder.school ;
            this.sex = builder.sex ;
        }
    }

    public static void main( String[] args ){
        Student a = new Student.StudentBuilder().setAge(13).setName("LiHua").build();
        Student b = new Student.StudentBuilder().setSchool("sc").setSex("Male").setName("ZhangSan").build();
    }
}
Lambada表示式
資料結構上增加@Builder註解
    public static void main( String[] args ){
        Student a = new Student.builder().age(13).name("LiHua").build();
    }

 

相關文章