首页 > 代码库 > 建造者模式案例

建造者模式案例

技术分享
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("一杯可乐");        
    }

}
MealA
技术分享
public class MealB extends MealBuilder{

    @Override
    public void buildFood() {
        getMeal().setFood("三个鸡翅");
        
    }

    @Override
    public void buildDrink() {
        getMeal().setDrink("一杯柠檬果汁");
    }

}
MealB
技术分享
//指挥者类
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());
                

    }
客户端

 

建造者模式案例