zoukankan      html  css  js  c++  java
  • 【Effective Java】2、构造参数过多的时候

    package cn.xf.cp.ch02.item2;
    
    /**
     * 
     * 功能:当我们的构造参数有很多,超出可控范围的时候,用build模式 时间:下午8:25:05 文件:NutritionFacts.java
     * 
     * @author Administrator
     *
     */
    public class NutritionFacts
    {
        private final int    param1;
        private final int    param2;
        private final int    param3;
        private final int    param4;
        private final int    param5;
        private final int    param6;
        private final int    param7;
    
        public static void main(String[] args)
        {
            // 初始化NutritionFacts
            NutritionFacts test = new NutritionFacts.Builder(1, 2).param3(3).param4(4).param5(5).param6(6).param7(7)
                    .build();
        }
    
        private NutritionFacts(Builder build)
        {
            param1 = build.param1;
            param2 = build.param2;
            param3 = build.param3;
            param4 = build.param4;
            param5 = build.param5;
            param6 = build.param6;
            param7 = build.param7;
        }
    
        public static class Builder
        {
            private final int    param1;
            private final int    param2;
            private int            param3    = 0;
            private int            param4    = 0;
            private int            param5    = 0;
            private int            param6    = 0;
            private int            param7    = 0;
    
            public Builder(int param1, int param2)
            {
                this.param1 = param1;
                this.param2 = param2;
            }
    
            public Builder param3(int val)
            {
                param3 = val;
                return this;
            }
    
            public Builder param4(int val)
            {
                param3 = val;
                return this;
            }
    
            public Builder param5(int val)
            {
                param3 = val;
                return this;
            }
    
            public Builder param6(int val)
            {
                param3 = val;
                return this;
            }
    
            public Builder param7(int val)
            {
                param3 = val;
                return this;
            }
    
            public NutritionFacts build()
            {
                return new NutritionFacts(this);
            }
        }
    }
  • 相关阅读:
    hdu acm 2639背包问题,这题很经典啊~~~
    hdu acm 2191
    qt中实现区域反白效果
    解决pythonxml 模块 在ubuntu karmic中找不到的问题
    Python正则表达式操作指南
    webkit 资料
    标点符号的英语名称
    ubuntu设置分辨率
    如何绑定多个action到一个slot
    改注册表,实现像迅雷一样的自定义url
  • 原文地址:https://www.cnblogs.com/cutter-point/p/5840167.html
Copyright © 2011-2022 走看看