美文网首页
Java Builder设计模式(实例)

Java Builder设计模式(实例)

作者: Mason啊 | 来源:发表于2018-11-16 10:40 被阅读10次
    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 NutritionFacts(Builder builder) {
            servingSize = builder.servingSize;
            servings = builder.servings;
            calories = builder.calories;
            fat = builder.fat;
            sodium = builder.sodium;
            carbohydrate = builder.carbohydrate;
        }
    
        public static class Builder {
            // required parameters
            private final int servingSize;
            private final int servings;
    
            // optional parameters
            private int calories;
            private int fat;
            private int sodium;
            private int carbohydrate;
    
            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 sodium(int val) {
                sodium = val;
                return this;
            }
    
            public Builder carbohydrate(int val) {
                carbohydrate = val;
                return this;
            }
    
            public NutritionFacts build() {
                return new NutritionFacts(this);
            }
        }
    
    
        public static void main(String[] args) {
            NutritionFacts build = new Builder(240, 8)
                    .fat(100)
                    .sodium(11)
                    .carbohydrate(12)
                    .build();
        }
    }
    

    相关文章

      网友评论

          本文标题:Java Builder设计模式(实例)

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