Builder好處就是能夠一次選配好幾個選項html
public class Student { private String name = ""; private String age = ""; private String sex = ""; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public Student() { } public Student(Builder builder) { name = builder.name; age = builder.age; } public static class Builder{ private String name = ""; private String age = ""; public Builder setName(String name){ this.name = name; return this; } public Builder setAge(String age){ this.age = age; return this; } public Student create(){ return new Student(this); } }; }
若是不適用Builder,建立一個對象賦值,須要好幾回完成,函數
Student student = new Student(); student.setAge("9"); student.setName("ha");
使用Builder一次就能夠配置完成ui
Student student = new Student.Builder().setName("ha").setAge("9").create();
固然,建立構造函數也能夠進行多參數賦值,但是當參數不少時,構造參數就會很長很亂。this
Builder優勢可在建立期間進行調整,還能夠根據對象不一樣而進行改變code
Builder缺點是確定會增長代碼量的htm