给出Dobbs 博士的这篇文章,特别是 Builder 模式,我们如何处理子类化 Builder 的情况?以我们想要子类化以添加 GMO 标签的示例的缩减版本为例,一个简单的实现将是:
public class NutritionFacts {
private final int calories;
public static class Builder {
private int calories = 0;
public Builder() {}
public Builder calories(int val) { calories = val; return this; }
public NutritionFacts build() { return new NutritionFacts(this); }
}
protected NutritionFacts(Builder builder) {
calories = builder.calories;
}
}
子类:
public class GMOFacts extends NutritionFacts {
private final boolean hasGMO;
public static class Builder extends NutritionFacts.Builder {
private boolean hasGMO = false;
public Builder() {}
public Builder GMO(boolean val) { hasGMO = val; return this; }
public GMOFacts build() { return new GMOFacts(this); }
}
protected GMOFacts(Builder builder) {
super(builder);
hasGMO = builder.hasGMO;
}
}
现在,我们可以编写如下代码:
GMOFacts.Builder b = new GMOFacts.Builder();
b.GMO(true).calories(100);
但是,如果我们弄错了顺序,一切都会失败:
GMOFacts.Builder b = new GMOFacts.Builder();
b.calories(100).GMO(true);
问题当然是NutritionFacts.Builder
返回 a NutritionFacts.Builder
,而不是 a GMOFacts.Builder
,那么我们如何解决这个问题,或者是否有更好的 Pattern 可以使用?
注意:this answer to a similar question提供了我上面的课程;我的问题是关于确保构建器调用顺序正确的问题。