程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> JAVA綜合教程 >> 【Effective Java】2、構造參數過多的時候,effectivejava

【Effective Java】2、構造參數過多的時候,effectivejava

編輯:JAVA綜合教程

【Effective Java】2、構造參數過多的時候,effectivejava


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

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved