美文网首页
初识构建者

初识构建者

作者: PeterHe888 | 来源:发表于2017-08-09 11:04 被阅读17次

    使用构建者的一种情况

    • 遇到多个构造器参数时考虑使用
      相关代码:
    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();
    

    相关文章

      网友评论

          本文标题:初识构建者

          本文链接:https://www.haomeiwen.com/subject/rbufrxtx.html