标签: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更加安全。
标签:auto val services his 客户端 span cal 阅读 构建
原文地址:http://www.cnblogs.com/mzxl1987/p/7803232.html