保证像重叠构造器模式那样的安全性,也能保证像JavaBeans模式那么好的可读性。Builder模式
将构造器设置为私有,通过构造内部静态类的方式,类似于JavaBean的写法,形成静态工厂模式。
就能同时拥有构造器的安全和JavaBean的可读性。
import com.sun.corba.se.impl.naming.cosnaming.NamingUtils;
/**
* Created by 95112 on 11/11/2017.
*/
public class NutritionFacts {
private final int servingSize;
private final int servings;
private final int calories;
private final int fat;
private final int sodium;
private final int carbohtdrate;
public static class Builder{
private final int servingSize;
private final int servings;
private int calories = 0;
private int fat = 0;
private int carbohydrate = 0;
private int sodium = 0;
public Builder(int servingSize,int servings){
this.servings = servings;
this.servingSize =servingSize;
}
public Builder calories(int val){
calories = val;
return this;
}
public Builder fat(int val){
fat = val;
return this;
}
public Builder carbohydrate(int val) {
carbohydrate = val;
return this;
}
public Builder sodium(int val)
{
sodium = val;
return this;
}
public NutritionFacts build(){
return new NutritionFacts(this);
}
}
private NutritionFacts(Builder builder){
servings = builder.servings;
servingSize = builder.servingSize;
calories = builder.calories;
fat = builder.fat;
sodium = builder.sodium;
carbohtdrate = builder.carbohydrate;
}
}
NutritionFacts n = new NutirtionFacts.Builder(1,2).calories(1).fat(2).carbohydrate(10).sodium(3).build();