易学设计模式五 建造模式(Builder)
遇到多个构造器参数(Constructor Parameters)时要考虑用构建器(Builder)
//营养素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 carbohydrate; //碳水化合物// 构造器,静态内部类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.servingSize = servingSize; this.servings = servings; } public Builder calories(int calories) { this.calories = calories; return this; } public Builder sodium(int sodium) { this.sodium = sodium; return this; } public Builder fat(int fat) { this.fat = fat; return this; } public Builder carbohydrate(int carbohydrate) { this.carbohydrate = carbohydrate; return this; } //最后返回构建成功的对象 public NutritionFacts build() { return new NutritionFacts(this); }}//私有构造子private NutritionFacts(Builder builder) {this.servingSize = builder.servingSize;this.servings = builder.servings;this.calories = builder.calories;this.fat = builder.fat;this.sodium = builder.sodium;this.carbohydrate = builder.carbohydrate;}@Override public String toString() { // TODO Auto-generated method stub return "["+ "servingSize:"+servingSize+ ",servings:"+servings+ ",calories:"+calories+ ",fat:"+fat+ ",sodium:"+sodium+ ",carbohydrate:"+carbohydrate+ "]"; }public static void main(String [] args) {NutritionFacts cocaCola = new NutritionFacts.Builder(240, 8).calories(100).sodium(35).carbohydrate(27).build();System.out.println(cocaCola.toString());}}