4

将构建器实例存储在它构建的实例中是否被认为是一种好习惯?问题是,当我需要创建一个与我已经拥有的对象非常相似的对象时,我经常发现自己处于一种情况。推测这个对象有很多 8-10 个字段。通常,对于可变对象,我只会使用 setter。

例如,让我们以经典的布洛赫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;
    }
}

我已经对其进行了一些修改,以便将来我想制作类似的副本时可以访问构建器实例?

你怎么看?

4

1 回答 1

6

如果您重用Builder来构建第二个实例会发生什么?然后Builder在第一个实例中将产生类似于第二个实例的实例。可能不是你所期望的。

我建议Builder使用模板实例创建一个选项。

    public Builder(NutritionFacts template) {
        this.servingSize = template.getServingSize();
        ...
    }
于 2012-09-13T11:55:36.897 回答