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 NutritionFacts(int servingSize, int servings){ this(servingSize, servings, 0); } public NutritionFacts(int servingSize, int servings, int calories){ this(servingSize, servings, calories, 0); } public NutritionFacts(int servingSize, int servings, int calories, int fat){ this(servingSize, servings, calories, fat, 0); } public NutritionFacts(int servingSize, int servings, int calories, int fat, int sodium){ this(servingSize, servings, calories, fat, sodium, 0); } public NutritionFacts(int servingSize, int servings, int calories, int fat, int sodium, int carbohydrate){ this.servingSize = servingSize; this.servings = servings; this.calories = calories; this.fat = fat; this.sodium = sodium; this.carbohydrate = carbohydrate; } }
如果想要创建实例对象的时候,就利用参数列表最短的构造方法:
1
NutritionFacts cocaCola = new NutritionFacts(240, 8, 100, 0, 35, 27);
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 final int calories = 0; private final int fat = 0; private final int sodium = 0; private final int carbohydrate = 0; public Builder(int servingSize, int servings){ this.servingSize = servingSize; this.servings = servings; } public Builder calories(int val){ this.calories = val; return this; } public Builder fat(int val){ this.fat = val; return this; } public Builder sodium(int val){ this.sodium = val; return this; } public Builder carbohydrate(int val){ this.carbohydrate = val; 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; } }
用建造者模式创建实例对象:
1 2
NutritionFacts cocaCola = new NutritionFacts().Build(240, 8).calories(100).sodium(35) .carbohydrate(27).build();