在您的情况下,请坚持使用构造函数。该信息属于客户,4 个字段都可以。
如果您有许多必需和可选字段,则构造函数不是最佳解决方案。正如@boojiboy 所说,很难阅读,也很难编写客户端代码。
@contagious 建议对可选属性使用默认模式和设置器。这要求字段是可变的,但这是一个小问题。
关于 Effective Java 2 的 Joshua Block 说,在这种情况下,您应该考虑使用构建器。书中的一个例子:
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
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;
soduim = builder.sodium;
carbohydrate = builder.carbohydrate;
}
}
然后像这样使用它:
NutritionFacts cocaCola = new NutritionFacts.Builder(240, 8).
calories(100).sodium(35).carbohydrate(27).build();
上面的例子取自Effective Java 2
这不仅适用于构造函数。在实现模式中引用 Kent Beck :
setOuterBounds(x, y, width, height);
setInnerBounds(x + 2, y + 2, width - 4, height - 4);
将矩形明确地作为一个对象来更好地解释代码:
setOuterBounds(bounds);
setInnerBounds(bounds.expand(-2));