我正在阅读Joshua Bloch撰写的Effective Java。在第16页的顶部,他说:
Note that our NutritionFacts.Builder class could be declared to implement
Builder<NutritionFacts>.
但是“Builder”如何实现“Builder”接口,因为那里存在名称空间冲突,例如:
public static class Builder implements Builder<NutritionFacts>...
我应该将内部静态类重命名为NutritionFacts.NutritionBuilder还是什么?
这是他提供的构建器模式:
// 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;
}
}
答案 0 :(得分:4)
您可以完全限定接口名称。
即:
public static class Builder implements my.package.Builder<NutritionFacts> {