实现
public class User {
private String id;
private String name;
private String phone;
private String addr;
public static Builder builder() {
return new Builder();
}
public static class Builder {
private String id;
private String name;
private String phone;
private String addr;
public User build() {
User user = new User();
user.id = this.id;
user.name = this.name;
user.phone = this.phone;
user.addr = this.addr;
return user;
}
public Builder id(String id) {
this.id = id;
return this;
}
public Builder name(String name) {
this.name = name;
return this;
}
public Builder phone(String phone) {
this.phone = phone;
return this;
}
public Builder addr(String addr) {
this.addr = addr;
return this;
}
}
public static void main(String[] args) {
User user = User.builder().id("1").name("2").addr("3").phone("4").build();
}
}
总结
- 使用静态内部类和静态方法可以直接通过类方法调用
- 封装对象构建细节
- 适用于构建对象时有特殊逻辑操作
网友评论