将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示
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();