通常我们在遇到构造器参数过多时我们会考虑使用重叠构造器与JavaBeans模式处理,但重叠构造器当参数过多时,会造成客户端代码难以编写。而JavaBeans虽然有利于客户端代码的开发,但是由于构造过程被分到了几个调用中,也就是JavaBeans模式阻止了把类做成不可变的可能,需要额外提供线程安全。例子代码如下:
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{
private final int servingSize;
private final int servings;
private int calories = 0;
private int fat = 0;
private int carbohydrate = 0;
private int sodium = 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 carbohydrate(int val){
carbohydrate = val;
return this;
}
public Builder sodium(int val){
sodium = val;
return this;
}
public NutritionFacts build(){
return new NutritionFacts(this);
}
}
private NutritionFacts(Builder builder){
servingSize = builder.servingSize;
sevings = builder.servings;
calories = builder.calories;
fat = builder.fat;
sodium = builder.sodium;
carbohydrate = builder.carbohydrate;
}
}
调用示例:
NutritionFacts cola = new NutritionFacts.Builder(240,8).calories(100).sodium(35).carbohydrate(27).build();