先上uml图
应用场景一:解决多构造函数的问题
如Person对象,在不同的场景需要使用到的参数不同,使用Set属性方式不优雅,如果属性值过多代码也会显得非常的冗余。
另一种实现方式是在构造函数中初始化属性,如果场景复杂,那么构造器也需要增加很多,使用起来非常不方便,使用Builder则会灵活很多。
public class Person {
private String idNo;
private String name;
private String phone;
private String cardNo;
public Person(Builder builder) {
this.idNo = builder.idNo;
this.name = builder.name;
this.phone = builder.phone;
this.cardNo = builder.cardNo;
}
public static class Builder {
private String idNo;
private String name;
private String phone;
private String cardNo;
public Builder idNo(String idNo) {
this.idNo = idNo;
return this;
}
public Builder name(String name) {
this.name = name;
return this;
}
public Builder phone(String phone) {
this.phone = phone;
return this;
}
public Builder cardNo(String cardNo) {
this.cardNo = cardNo;
return this;
}
public Person build() {
return new Person(this);
}
}
public String getIdNo() {
return idNo;
}
public void setIdNo(String idNo) {
this.idNo = idNo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getCardNo() {
return cardNo;
}
public void setCardNo(String cardNo) {
this.cardNo = cardNo;
}
@Override
public String toString() {
return "Person [idNo=" + idNo + ", name=" + name + ", phone=" + phone + ", cardNo=" + cardNo + "]";
}
}
Director代码如下
Person person = new Person.Builder()
.name("张三三")
.phone("155510311122")
.idNo("10101010100100")
.build();