Build模式练习

/**
* Build模式练习
* @author Administrator
*
*/
public class NutritionFacts{
private int servingSize;
private int servings;
private int calories;
private int fat;
private int sodium;
private int carbohydrate;

public static class Builder{
private int servingSize=0;
private int servings=0;
private int calories=0;
private int fat=0;
private int sodium=0;
private int carbohydrate=0;

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

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

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

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

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

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

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

private NutritionFacts(Builder build){
this.servingSize=build.servingSize;
this.servings=build.servings;
this.calories=build.calories;
this.fat=build.fat;
this.sodium=build.sodium;
this.carbohydrate=build.carbohydrate;
}

public static void main(String[] args) {
NutritionFacts facts=new NutritionFacts.Builder().servings(100).sodium(10).carbohydrate(20).build();
System.out.println(facts.servings+","+facts.sodium+","+facts.carbohydrate);
}
}

你可能感兴趣的:(java,应用)