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

      

  • 相关阅读:
    为什么叫 React Hooks
    谈谈 Promise 以及实现 Fetch 的思路
    Mac使用tree查看目录结构
    Mac下Nginx安装教程
    Mac包管理工具brew的安装、使用及换源
    Mac安装cnpm
    10分钟快速搭建可用的springboot-web项目
    【转载】ibit-mybatis介绍
    【转载】sql-builder介绍
    Java软件工程师技能图谱
  • 原文地址:https://www.cnblogs.com/frankyou/p/6912992.html
Copyright © 2011-2022 走看看