码迷,mamicode.com
首页 > 其他好文 > 详细

遇到多个构造器参数可用考虑builder模式

时间:2017-11-08 13:20:20      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:auto   val   services   his   客户端   span   cal   阅读   构建   


public class NutritionFacts {

private final int serviceSize;
private final int servings;
private final int calories;
private final int fat;

public static class Builder {
  private final int serviceSize;
  private final int servings;

  private int calories = 0;
  private int fat = 0;

  public Builder(int serviceSize, int servings) {
    this.serviceSize = serviceSize;
    this.servings = servings;
  }

  public Builder calories(int val) {
    calories = val;
    return this;
  }

  public Builder fat(int val) {
    fat = val;
    return this;
  }

  public NutritionFacts build() {
    return new NutritionFacts(this);
  }

}

public NutritionFacts(Builder build) {
  // TODO Auto-generated constructor stub
  this.serviceSize = build.serviceSize;
  this.servings = build.servings;
  this.calories = build.calories;
  this.fat = build.fat;
}

public static void main(String[] args) {
  // TODO Auto-generated method stub
  NutritionFacts nutr = new NutritionFacts.Builder(0,0)
  .fat(0)
  .calories(0)
  .build();

  }

}

简而言之,如果类的构造器或者静态工厂中有很多参数,设计这种类时,Builder模式是很不错的选择,特别是当大多数参数都是可选的时候。与使用传统的重叠构造器模式相比,用Builder模式的客户端代码将更已于阅读和编写,构建器也比JavaBean更加安全。

 

遇到多个构造器参数可用考虑builder模式

标签:auto   val   services   his   客户端   span   cal   阅读   构建   

原文地址:http://www.cnblogs.com/mzxl1987/p/7803232.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!