• 建造者模式案例


    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());
                    
    
        }
    客户端

      具体案例说明及文档在文件中:

    MyBuilder建造者.rar 58KB 1/7/2017 6:49:24 PM
  • 相关阅读:
    java文件配置MySQL
    logback.xml
    Apache Commons之commons-lang
    Codec入门
    Mysql命令增加、修改、删除表字段
    markDown的简单使用
    Vert.x核心包各功能模块详解
    StringJoiner使用详解
    Vert.x初体验
    Docker镜像备份与迁移
  • 原文地址:https://www.cnblogs.com/WuXuanKun/p/6062992.html
Copyright © 2020-2023  润新知