给这篇多布斯博士文章,特别是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
返回NutritionFacts.Builder
,而不是a GMOFacts.Builder
,那么我们如何解决这个问题,还是有更好的Pattern来使用?
注意:这个类似问题的答案提供了我上面的课程;我的问题是有关确保构建器调用顺序正确的问题。
build()
的输出如何b.GMO(true).calories(100)
?