• 学习记录--遇到多个构造参数时考虑用构建器


    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 servings;
    
            private int calories = 0;
    
            private int fat = 0;
    
            private int sodium = 0;
    
            private int carbohydrate = 0;
    
            public Builder(int servingSize, int servings) {
                super();
                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);
            }
        }
    
        private NutritionFacts(Builder builder) {
            servingSize = builder.servingSize;
            servings = builder.servings;
            calories = builder.calories;
            fat = builder.fat;
            carbohydrate = builder.carbohydrate;
            sodium = builder.sodium;
        }
    
        public static void main(String[] args) {
            NutritionFacts cocaCola = new NutritionFacts.Builder(240, 8).calories(23).sodium(5).build();
        }
    }
    

      

  • 相关阅读:
    浏览器兼容性问题
    浏览器对象的属性和方法
    js总结体会
    css样式总结体会
    HTML标签类总结
    如何自动化实现二级域名访问,类似博客
    php
    require.js
    gulp
    javascript
  • 原文地址:https://www.cnblogs.com/ly-radiata/p/5669223.html
Copyright © 2020-2023  润新知