例如有这个一个类的构造函数:
public Register(int id, int age, String name, String address, String like, int high, int weight)
那么此时的做法:
new Register(1, 20, "A", "B", "C", 170, 60);
这样的缺点就是:
- 参数会很乱,调用者很容易搞错参数的位置
- 如果不想为某个参数赋值,那么你还是要赋值,除非你另写一个没有该值的构造函数
Builder模式
public class Register {
private int id;
private int age;
private String name;
private String address;
private String like;
private int high;
private int weight;
public static class Builder {
private int id;
private String name;
private int age;
private String address;
private String like;
private int high;
private int weight;
public Builder(int id, String name) {
this.id = id;
this.name = name;
}
public Builder age(int age){
this.age = age;
return this;
}
public Builder address(String address){
this.address = address;
return this;
}
public Builder like(String like){
this.like = like;
return this;
}
public Builder high(int high){
this.high = high;
return this;
}
public Builder weight(int weight){
this.weight = weight;
return this;
}
public Register build(){
return new Register(this);
}
}
//私有化
private Register(Builder builder){
id = builder.id;
name = builder.name;
age = builder.age;
address = builder.address;
like = builder.like;
high = builder.high;
weight = builder.weight;
}
}
此时的用法:
Register re = new Register.Builder(1, "liu").age(20).address("LA").like("Ball").high(180).build();
lombok.Builder 的 @Builder实现
网友评论