Meal:
public class Meal { private String food; private String drink; public void setFood(String food){ this.food = food; } public String getFood(){ return food; } public void setDrink(String drink){ this.drink = drink; } public String getDrink(){ return drink; } }
MealBuilder:
public abstract class MealBuilder { private Meal meal = new Meal(); public abstract void buildFood(); public abstract void buildDrink(); public Meal getMeal(){ return meal; } }
SubMealBuilderA:
public class SubMealBuilderA extends MealBuilder { @Override public void buildFood() { System.out.println("This is SubMealBuilderA food!"); } @Override public void buildDrink() { System.out.println("This is SubMealBuilderA Drink!"); } }
SubMealBuilderB:
public class SubMealBuilderB extends MealBuilder{ @Override public void buildFood() { System.out.println("This is SubMealBuilderB food!"); } @Override public void buildDrink() { System.out.println("This is SubMealBuilderB drink!"); } }
KFCWaiter:
public class KFCWaiter { private MealBuilder mb = null; public KFCWaiter(){ } public KFCWaiter(MealBuilder mb){ this.mb = mb; } public void setMealBuilder(MealBuilder mb){ this.mb = mb; } public Meal construct(){ mb.buildDrink(); mb.buildFood(); return mb.getMeal(); } }
BuilderMethod(调用):
public class BuilderMethod{ public static void main(String[] args){ MealBuilder mb_1 = new SubMealBuilderA(); MealBuilder mb_2 = new SubMealBuilderB(); KFCWaiter kfc = null; kfc = new KFCWaiter(mb_1); kfc.construct(); kfc = new KFCWaiter(mb_2); kfc.construct(); } }
Result:
This is SubMealBuilderA Drink!
This is SubMealBuilderA food!
This is SubMealBuilderB drink!
This is SubMealBuilderB food!