將一個複雜對象的構建與它的表示分離,使得同樣的構建過程可以創建不同的表示
public Person(String name) {
this.name = name;
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public Person(String name, int age, String sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
比如上代碼要實現多個不同參數的構造方法需要多個不同參數的構造方法,不夠靈活,代碼量也大
public class Person {
public Person(Builder builder) {
name = builder.name;
age = builder.age;
sex = builder.sex;
}
private String name;
private int age;
private String sex;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public static class Builder{
private String name;
private int age;
private String sex;
public Builder name(String name){
this.name = name;
return this;
}
public Builder age(int age){
this.age = age;
return this;
}
public Builder sex(String sex){
this.sex = sex;
return this;
}
public Person Build(){
return new Person(this);
}
}
}
Person.Builder builder = new Person.Builder();
Person person = builder
.age(19)
.name("liu")
.sex("nv")
.Build();
很熟悉的方式
以上代碼是通過構建者模式實現的多個不同參數的方法,等同於構建了不同參數的構造方法
Android原生的AlertDialog也是通過構造者模式實現的
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
AlertDialog dialog = dialogBuilder
.setTitle("title")
.create();