//构建器抽象类,为不同类的实现提供 public interface Builder<T> { public T build(); } /** * @描述: 营养表 */ public class NutritionFacts { private final int servingSize;// required private final int servings;// required private final int calories;// optional private final int fat;// optional private final int sodium;// optional private final int carbohydrate;// optional public static class Builder1 implements Builder<NutritionFacts>{ private final int servingSize;// required 食用分量 private final int servings;// required (食品等的)一份 private int calories;// optional 卡路里 private int fat;// optional private int sodium;// optional 钠 private int carbohydrate;// optional 碳水化合物;糖类 public Builder1(int servingSize,int servings){ this.servingSize = servingSize; this.servings = servings; } public Builder1 calories(int calories) { this.calories = calories; return this; } public Builder1 fat(int fat) { this.fat = fat; return this; } public Builder1 sodium(int sodium) { this.sodium = sodium; return this; } public Builder1 carbohydrate(int carbohydrate) { this.carbohydrate = carbohydrate; return this; } @Override public NutritionFacts build() { return new NutritionFacts(this); } } private NutritionFacts(Builder1 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; } public static void main(String[] args) { NutritionFacts cocacola = new NutritionFacts.Builder1(240, 80).calories(100).sodium(35).carbohydrate(27).build(); } } 为非必须参数设置值,返回Build自身可以把调用链接起来 好处: 1、可以用单个builder创建多个对象,builder的参数可以在创建对象期间调整,可以随着对象不同而改变。builder可以自动填充某些域,例如每次创建对象时自动增加序号。 2、这是一个很好的抽象工厂(abstract factory)。客户端只要将这样一个builder传给方法,该方法能为客户端创建一个或多个对象。 一个通用类型的bulider public interface Builder<T>{ public T build(); }