初识构建者

使用构建者的一种情况

  • 遇到多个构造器参数时考虑使用
    相关代码:
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 {
        private final int servingSize;
        private final int serving;

        private int calories = 0;
        private int fat = 0;
        private int sodium = 0;
        private int carbonhydrate;

        public Builder(int servingSize, int serving) {
            this.servingSize = servingSize;
            this.serving = serving;
        }

        public Builder calories(int val) {
            calories = val;
            return this;
        }
        public Builder fat(int val) {
            fat = val;
            return this;
        }
        public Builder sodium(int val) {
            sodium = val;
            return this;
        }
        public Builder carbonhydrate(int val) {
            carbonhydrate = val;
            return this;
        }

        public NutritionFacts build() {
            return new NutritionFacts(this);
        }

    }

    private NutritionFacts(Builder builder) {
        servingSize = builder.servingSize;
        servings = builder.serving;
        calories = builder.calories;
        fat = builder.fat;
        sodium = builder.sodium;
        carbohydrate = builder.carbonhydrate;
    }
}

调用方法:

NutritionFacts nutritionFacts = new NutritionFacts.Builder(230, 4).
                calories(0).fat(0).sodium(0).carbonhydrate(0).build();

你可能感兴趣的:(初识构建者)