你的位置:首页 > Java教程

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