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