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

  

原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/15972.html

(0)
上一篇 2021年7月19日
下一篇 2021年7月19日

相关推荐

发表回复

登录后才能评论