java模式:建造者模式

  我發現不少源碼很喜歡用這個模式,好比spring cloud,spring framework。html

  建造者模式(Builder)用以構建各類各樣的對象,主要功能就是代替對象的構造函數,更加自由化。spring

  舉個栗子,先假設有一個問題,咱們須要建立一個學生對象,屬性有name,number,class,sex,age,school等屬性,若是每個屬性均可覺得空,也就是說咱們能夠只用一個name,也能夠用一個school,name,或者一個class,number,或者其餘任意的賦值來建立一個學生對象,這時該怎麼構造?函數

  難道咱們寫6個1個輸入的構造函數,15個2個輸入的構造函數.......嗎?這個時候就須要用到Builder模式了。ui

  例子借用:https://www.cnblogs.com/malihe/p/6891920.htmlthis

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();
    }
}
相關文章
相關標籤/搜索