zoukankan      html  css  js  c++  java
  • The Builder pattern simulates named optional parameters(Java)

    the Builder pattern is a good choice when designing classes whose constructors or static factories would have more than a handful of parameters.

    /**
     * Created by xfyou 2017/5/27 14:41 14:42.
     * The Builder pattern simulates named optional parameters
     */
    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 {
            // 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) {
                this.calories = val;
                return this;
            }
    
            public Builder carbohydrate(int val) {
                this.carbohydrate = val;
                return this;
            }
    
            public Builder sodium(int val) {
                this.sodium = val;
                return this;
            }
    
            public NutritionFacts build() {
                return new NutritionFacts(this);
            }
        }
    
        public NutritionFacts(Builder builder) {
            this.calories = builder.calories;
            this.carbohydrate = builder.carbohydrate;
            this.fat = builder.fat;
            this.servings = builder.servings;
            this.servingSize = builder.servingSize;
            this.sodium = builder.sodium;
        }
    
        public int getServingSize() {
            return servingSize;
        }
    
        public int getServings() {
            return servings;
        }
    
        public int getCalories() {
            return calories;
        }
    
        public int getFat() {
            return fat;
        }
    
        public int getSodium() {
            return sodium;
        }
    
        public int getCarbohydrate() {
            return carbohydrate;
        }
    }
    

      

  • 相关阅读:
    es6-字符串常用方法
    新增行数据校验
    python-Django路由传参
    递归算法
    CSS动画效果
    克隆远程仓库
    添加git仓库
    滚动条——overflow:auto 自定义样式
    CSS——链接伪类选择器
    进程,线程,同步 ,异步
  • 原文地址:https://www.cnblogs.com/frankyou/p/6912992.html
Copyright © 2011-2022 走看看