重叠构造器模式可行,但是当有许多参数的时候,客户端代码会很难编写
Builder模式:
不直接生成想要的对象,而是让客户端利用所有必要的参数调用构造器,得到一个builder对象。
public class NutritionFacts {
private final int servingSize;
private final int servings;
private final int calories;
private final int fat;
private final int sodium;
private final int carbohydrate;
public static class Builder{
//required params
private final int servingSize;
private final int servings;
//optional params --need to initialize
private int calories = 0 ;
private int fat = 0;
private int sodium = 0;
private int carbohydrate = 0;
public Builder(int servingSize,int servings) {
this.servingSize = servingSize;
this.servings = servings;
}
public Builder calories(int val) {
calories = val;
return this;
}
public Builder fat(int val) {
fat = val;
return this;
}
public Builder sodium(int val) {
sodium = val;
return this;
}
public Builder carbohydrate(int val) {
carbohydrate = val;
return this;
}
public NutritionFacts build() {
return new NutritionFacts(this);
}
}
private NutritionFacts(Builder builder) {
servingSize = builder.servingSize;
servings = builder.servings;
calories = builder.calories;
fat = builder.fat;
sodium = builder.sodium;
carbohydrate = builder.carbohydrate;
}
}
注意NutritionFacts是不可变的,所有的默认参数值都单独放在一个地方。builder的setter方法返回builder本身,以便可以把调用链接起来。
下面就是客户端代码:
NutritionFacts nutritionFacts = new NutritionFacts.Builder(1, 1).calories(1).sodium(20).build();
与构造器相比,builder的微略的优势在于,builder可以有多个可变的参数。构造器就像方法一样,,只能有一个可变参数,因为builder利用单独的方法来设置每个参数,你想要多少个可变参数,他们就可以有多少个,直到每个setter方法都有一个可变参数。