Java 繁琐写法
@Data
public class People {
private String name;
private Integer age;
private String sex;
private String address;
private String phoneNo;
public static class PeopleBuilder {
// 必选参数
private String name;
private Integer age;
// 可选参数
private String sex;
private String address;
private String phoneNo;
public PeopleBuilder(String name, Integer age) {
this.name = name;
this.age = age;
}
public PeopleBuilder sex(String sex) {
this.sex = sex;
return this;
}
public PeopleBuilder address(String address) {
this.address = address;
return this;
}
public PeopleBuilder phoneNo(String phoneNo) {
this.phoneNo = phoneNo;
return this;
}
public People build() {
return new People(this);
}
}
private People(PeopleBuilder peopleBuilder) {
this.name = peopleBuilder.name;
this.age = peopleBuilder.age;
this.address = peopleBuilder.address;
this.sex = peopleBuilder.sex;
this.phoneNo = peopleBuilder.phoneNo;
}
public static void main(String[] args) {
People people = new PeopleBuilder("Jone", 30).address("hz").build();
System.out.println(people.getName());
}
}
lombok 之 @Builder
@Builder
@Data
public class People {
private String name;
private Integer age;
private String sex;
private String address;
private String phoneNo;
public static void main(String[] args) {
People people = People.builder().address("hz").phoneNo("123").build();
System.out.println(people.getPhoneNo());
}
}
- 重叠构造器模式
特点:若干个构造方法,最短的一个参数,最长的包含所有参数
缺点:显而易见,难以阅读
- JavaBeans模式
特点:一个无参数的构造函数加各种setter 方法。
缺点:构造方法在多次调用中被分割,所以在构造过程中JavaBean可能处于不一致的状态
- builder 模式
Builder模式既能保证像重叠构造器模式那样的安全性,也能保证像JavaBeans模式那么好的可读性。Builder模式不直接生成想要的对象,而是让客户端利用所有必要的参数调用构造器(或者静态工厂),得到一个builder对象。然后客户端在builder对象上调用类似于setter的方法,来设置每个相关的可选参数。最后,客户端调用无参的builder方法来生成不可变的对象。