zoukankan      html  css  js  c++  java
  • 《Effective Java》之Builder Pattern

    如果类的构造器或静态工厂具有多个输入参数,在调用Object(1.0,2.0,3.0,4.0,5.0,6.0)的时候你也许会记不住这么多参数具体对应的属性,再者如果一个类具有较多的需要初始化的属性的时候,那么它的构造函数想必也是需要多个(依然免不了前面看起来较多的参数传入),你需要实现具有1,2,,,个参数的构造函数。

    那么接下来这样的方法也许能够改变你上面的烦恼。

    1.需要构造的类如下:

    
    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 servingSzie,int serings) {
                this.servingSize=servingSzie;
                this.servings=serings;
            }
            public Builder calories(int calories) {
                this.calories=calories;
                return this;
            }
            public Builder fat(int fat) {
                this.fat=fat;
                return this;
            }
            public Builder sodium(int sodium) {
                this.sodium=sodium;
                return this;
            }
            public Builder carbohydrate(int carbohydrate) {
                this.carbohydrate=carbohydrate;
                return this;
            }
            public NutritionFacts builder() {
                return new NutritionFacts(this);
            }
        }
        public NutritionFacts(Builder builder) {
            servingSize=builder.servingSize;
            servings=builder.servings;
            calories=builder.calories;
            fat=builder.fat;
            sodium=builder.sodium;
            carbohydrate=builder.carbohydrate;
        }
    }
    

    2.调用生成对象如下:

    
    public class Main {
    
        public static void main(String[] args) {
            //分别设置每一个参数,
            NutritionFacts nutritionFacts=new NutritionFacts.Builder(15, 20).
                    calories(1).carbohydrate(2).fat(3).sodium(4).builder();
        }
    
    }
    

    参考资料:
    《Effective Java》

  • 相关阅读:
    js中null " "的区别
    简略的地图API应用
    JSON的一个例子(代码来源于网上)
    浅谈Event Flow、Process、Method及其Applications
    JS中object与constructor的分析
    浅谈for...in与for....of
    浅谈语言的过去与未来
    正则表达式的四个小应用
    BOM详细
    BOM
  • 原文地址:https://www.cnblogs.com/lizijuna/p/11907420.html
Copyright © 2011-2022 走看看