星空网 > 软件开发 > Java

遇到多个构造器参数时要考虑用构造器

一般的重叠构造器模式:

 

public class NutritionFacts{  private final int one;  private final int two;  private final int three;  public NutritionFacts(int one,int two,int three){   this.one = one;   this.two = two;      }  public NutritionFacts(int one){   this(one,0);  }  public NutritionFacts(int one,int two){   this(one,two,0);  }}//调用的时候 NutritionFacts nt = new NutritionFacts(0,0,0);//缺点 :重叠构造器模式,有许多参数的时候,难编写和阅读;

改进:Builder模式:

public class NutritionFacts{  private final int one;  private final int two;  private final int three;   private NutritionFacts(Bulider builder){   one = builder.one;   two = builder.two;   three = builder.three;  }   public static class Builder{   private String name;   private int one = 0;   private int two = 0 ;   private int three = 0;   public Builder(String name){    this.name = name;   }   public Builder one(int value){     one = value;     reture this;   }   public Builder two(int value){     two = value;     reture this;   }   public Builder two(int value){     two = value;     reture this;   }   //调用的时候,最后实例化外部类   public NutritionFacts build(){    return new NutritionFacts(this);   }     }}




原标题:遇到多个构造器参数时要考虑用构造器

关键词:

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

shoppy外贸自建站:https://www.goluckyvip.com/tag/25324.html
Shops:https://www.goluckyvip.com/tag/25325.html
Shopspy:https://www.goluckyvip.com/tag/25326.html
ShopStyle:https://www.goluckyvip.com/tag/25327.html
Shopswain:https://www.goluckyvip.com/tag/25328.html
Shopsy:https://www.goluckyvip.com/tag/25329.html
怪物在游轮上复活的电影 怪物在游轮上复活的电影叫什么:https://www.vstour.cn/a/411230.html
在线旅游如何选择更优惠的旅游产品?:https://www.vstour.cn/a/411231.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流