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;
        }
    }
    

      

  • 相关阅读:
    字符串的不可变性--转载
    this的作用--转载
    构造函数
    根基决定一个程序员会不会被淘汰 --转载
    BAT-使用BAT方法清理Delphi临时文件
    键盘,鼠标,文件
    画布.画笔.画刷
    Delphi外挂开发网站
    教程-经典Delphi教程网
    教程-Delphi各版本与工具下载地址
  • 原文地址:https://www.cnblogs.com/frankyou/p/6912992.html
Copyright © 2011-2022 走看看