建造者模式案例
Posted WuXuanKun
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了建造者模式案例相关的知识,希望对你有一定的参考价值。
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()); }
具体案例说明及文档在文件中:
MyBuilder建造者.rar | 58KB | 1/7/2017 6:49:24 PM |
以上是关于建造者模式案例的主要内容,如果未能解决你的问题,请参考以下文章