3 回答

TA貢獻(xiàn)1862條經(jīng)驗(yàn) 獲得超6個(gè)贊
您可以使用泛型來(lái)解決它。我認(rèn)為這被稱為“奇怪的反復(fù)出現(xiàn)的通用模式”
使基類構(gòu)建器方法的返回類型成為通用參數(shù)。
public class NutritionFacts {
private final int calories;
public static class Builder<T extends Builder<T>> {
private int calories = 0;
public Builder() {}
public T calories(int val) {
calories = val;
return (T) this;
}
public NutritionFacts build() { return new NutritionFacts(this); }
}
protected NutritionFacts(Builder<?> builder) {
calories = builder.calories;
}
}
現(xiàn)在使用派生類構(gòu)建器作為泛型參數(shù)來(lái)實(shí)例化基礎(chǔ)構(gòu)建器。
public class GMOFacts extends NutritionFacts {
private final boolean hasGMO;
public static class Builder extends NutritionFacts.Builder<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;
}
}
添加回答
舉報(bào)