将构建器实例存储在其所构建的实例内是否被认为是良好的做法?事实上,当我需要创建一个与我已经拥有的非常相似的对象时,我经常会遇到这种情况。假设这个对象有8-10个字段。通常,对于可变对象,我只需使用setter方法即可。
例如,让我们来看看经典的Bloch的NutricionFacts
示例:
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;
private final Builder builder;
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;
this.builder = builder;
}
}
我对它进行了一些修改,这样如果我想在未来制作类似的副本,我就可以访问生成器实例了。
你觉得怎么样?