首页 > 代码库 > 建造者模式案例
建造者模式案例
private String food;//食物 private String drink;//饮料 public String getFood() { return food; } public void setFood(String food) { this.food = food; } public String getDrink() { return drink; } public void setDrink(String drink) { this.drink = drink; }
/** * @author megustas *抽象建造者类,确定套餐由两个产品buildFood()和buildDrink()组成,并声明一个得到产品建造后结果的方法getMeal() */ public abstract class MealBuilder { Meal meal=new Meal(); public abstract void buildFood(); public abstract void buildDrink(); public Meal getMeal() { return meal; } }
//建造具体的套餐产品buildFood()和产品buildDrink() public class MealA extends MealBuilder{ @Override public void buildFood() { getMeal().setFood("一盒薯条"); } @Override public void buildDrink() { getMeal().setDrink("一杯可乐"); } }
public class MealB extends MealBuilder{ @Override public void buildFood() { getMeal().setFood("三个鸡翅"); } @Override public void buildDrink() { getMeal().setDrink("一杯柠檬果汁"); } }
//指挥者类 public class KFCWaiter { private MealBuilder mealBuilder; //用来指挥建造过程 public Meal construct(){ mealBuilder.buildFood();//准备食物 mealBuilder.buildDrink();//准备饮料 return mealBuilder.getMeal();//准备完毕,返回一个完整的套餐给客户。 } public MealBuilder getMealBuilder() { return mealBuilder; } public void setMealBuilder(MealBuilder mealBuilder) { this.mealBuilder = mealBuilder; } }
/** * @param args * 客户端代码,客户不需知道具体的建造过程 */ public static void main(String[] args) { //服务员 KFCWaiter waiter=new KFCWaiter(); //套餐A MealA meala=new MealA(); //服务员准备套餐A waiter.setMealBuilder(meala); //获取套餐 Meal meal=waiter.construct(); System.out.println("套餐A的组成部分:"+meal.getFood()+"---"+meal.getDrink()); }
建造者模式案例
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。