Item2 :当构造方法中的参数列表太多时,考虑使用 builder 。
当一个类的构造方法有大量的(可选)参数时,通常考虑的方法有两种,一种是层叠的构造方法模式( telescope constructor ),一种是 JavaBean 模式。
这两种方法都有各自的缺陷,层叠的构造方法可读性差且容易出错; JavaBean 则会妨碍一个类成为不可变的类。
下面是一个使用 builder 的示例:
// Builder Pattern
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 parameters
private final int servingSize;
private final int servings;
// Optional parameters - initialized to default values
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;
servings = builder.servings;
calories = builder.calories;
fat = builder.fat;
sodium = builder.sodium;
carbohydrate = builder.carbohydrate;
}
}
可以是用这样的方式来创建这个类的实例:
NutritionFacts cocaCola = new NutritionFacts
.Builder(240, 8)
.calories(100)
.sodium(35)
.carbohydrate(27)
.build();
builder 模式的缺点是需要首先构造一个 Builder 对象,从某些方面来说这也是一种浪费?