美文网首页
【Effective JAVA】构造参数中多个变量可选时,用Bu

【Effective JAVA】构造参数中多个变量可选时,用Bu

作者: 彩虹妹妹qyf | 来源:发表于2018-05-16 11:23 被阅读11次

    【Builder模式介绍】
    不直接生产想要的对象,而是让客户端利用所有必要的参数调用构造器,得到一个builder对象。然后客户端在builder对象上调用类似setter的方法,来设置每个相关的可选参数。最后,客户端调用午餐的build方法来生成不可变的对象。这个builder就是它构建的类的静态成员类。
    【示例】

    public class BuilderPattern
    {
        private final int servingSize;
        private final int servings;
        private final int calories;
        private final int fat;
    
        public static class Builder
        {
            //必填参数
            private final int servingSize;
            private final int servings;
    
            //可选参数,设置默认值
            private int calories = 0;
            private int fat = 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 fat(int val)
            {
                this.fat = val;
                return this;
            }
    
            public BuilderPattern build()
            {
                return new BuilderPattern(this);
            }
        }
    
        private BuilderPattern(Builder builder)
        {
            this.servingSize = builder.servingSize;
            this.servings = builder.servings;
            this.calories = builder.calories;
            this.fat = builder.fat;
        }
    
        public void myPrint()
        {
            System.out.println("servingSize = "+servingSize+", servings = "+servings+", calories = " +
                    +calories+", fat = "+fat);
        }
    
        public static void main(String[] args)
        {
            BuilderPattern bp = new Builder(240,8).calories(100).fat(35).build();
            bp.myPrint();
        }
    }
    

    相关文章

      网友评论

          本文标题:【Effective JAVA】构造参数中多个变量可选时,用Bu

          本文链接:https://www.haomeiwen.com/subject/iyufdftx.html