构建器模式
// 定义
public class User {
private final Integer id;
private final String name;
private Integer age;
private String sex;
private String phone;
private User(UserBuilder builder){
this.id=builder.id;
this.name=builder.name;
this.age=builder.age;
this.sex=builder.sex;
this.phone=builder.phone;
}
public static class UserBuilder{
private final Integer id;
private final String name;
private Integer age;
private String sex;
private String phone;
public UserBuilder(Integer id,String name){
this.id=id;
this.name=name;
}
public UserBuilder age(Integer age){
this.age=age;
return this;
}
public UserBuilder sex(String sex){
this.sex=sex;
return this;
}
public UserBuilder phone(String phone){
this.phone=phone;
return this;
}
public User build(){
return new User(this);
}
}
}
// 使用
User.UserBuilder builder=new User.UserBuilder(222,"bbb");
User user=builder.phone("aaa").age(333).sex("cccc").build();
- 构建器模式优点
- 为了解决安全性问题,使用final限制属性不可变并移除setter方法等;
- 为了解决可读性和扩展性问题,通过使用静态嵌套类,在其中设置可变参数方法等;
- 相对于传统的setter/getter方法,
- 传统的方式成员变量不可以是 final 类型,失去了不可变对象的很多好处;。
- 对象状态不连续:你必须调用7次setter方法才能得到一个具备7个属性值得变量,在这期间用户可能拿到不完整状态的对象。如果有N个属性,岂不是要person.setXXX调用N次?此种方式不优雅。