标签:
程序的UML图:
代码:
public interface IMealBuilder { public void BuildBurger(); public void BuildChips(); public void BuildDrink(); Meal GetMeal(); }//首先先创建一个建造者接口IMealBuilder来创建套餐
public class Meal { private List<IFood> foodList=new ArrayList<IFood>(); public void addFood( IFood food ) { foodList.add(food); } public void Show() { for (int i=0; i<foodList.size(); i++) { foodList.get(i).Make(); } } }//用Meal类存放建造者需要建造的食物
public class KFCBuilder implements IMealBuilder { protected Meal meal=new Meal(); public void BuildBurger() { IFood food = new KFCBurger(); meal.addFood(food); } public void BuildChips() { IFood food = new KFCChips(); meal.addFood(food); } public void BuildDrink() { IFood food = new KFCDrink(); meal.addFood(food); } public Meal GetMeal() { return meal; } }//肯德基建造者KFCBuilder继承的建造过程IMealBuilder
public class McDonaldBuilder implements IMealBuilder { protected Meal meal=new Meal(); public void BuildBurger() { IFood food = new McDonaldBurger(); meal.addFood(food); } public void BuildChips() { IFood food = new McDonaldChips(); meal.addFood(food); } public void BuildDrink() { IFood food = new McDonaldDrink(); meal.addFood(food); } public Meal GetMeal() { return meal; } }//麦当劳建造者McDonaldBuilder继承的建造过程IMealBuilder
public class MealDirector { private IMealBuilder _builder; public MealDirector( IMealBuilder builder ) { _builder = builder; } public Meal CreateMeal() { _builder.BuildBurger(); _builder.BuildChips(); _builder.BuildDrink(); return _builder.GetMeal(); } }//创建一个指挥者MealDirector负责控制产品创建
public interface IFood { public abstract void Make(); }//创建一个食物的接口IFood,具有制作食物的方法Make()
public class KFCBurger implements IFood { public void Make() { System.out.println("KFC汉堡做好了!"); } }//肯德基各种食品的制作方法。
public class KFCChips implements IFood { public void Make() { System.out.println("KFC薯条做好了!"); } }//KFCChips
public class KFCDrink implements IFood { public void Make() { System.out.println("KFC饮料做好了!"); } }//KFCDrink
public class McDonaldBurger implements IFood { public void Make() { System.out.println("McDonald汉堡做好了!"); } }//麦当劳各种食品的制作方法
public class McDonaldChips implements IFood { public void Make() { System.out.println("McDonald薯条做好了!"); } }//McDonaldChips
public class McDonaldDrink implements IFood { public void Make() { System.out.println("McDonald饮料做好了!"); } }//McDonaldDrink
public class Main { public static void main(String[] args) { IMealBuilder builder1 = new KFCBuilder(); MealDirector director1 = new MealDirector(builder1); director1.CreateMeal().Show();; IMealBuilder builder2 = new McDonaldBuilder(); MealDirector director2 = new MealDirector(builder2); director2.CreateMeal().Show(); } }//主函数Main分别创建肯德基和麦当劳的建造者和指挥者,来制作各自的套餐
输出结果:
标签:
原文地址:http://www.cnblogs.com/fanghaibin/p/5090425.html