当先锋百科网

首页 1 2 3 4 5 6 7

    建造者模式属于创建型模式
    基本原理:有底到高一层层的创建叠加,上层是依靠底层的创建。就如细胞组成人体不同的组织,组织组成了不同的人。
    主要流程:
            1.建立最基本的单元
            2.建立所要建造的物品,使用基本单元创建该物品的元素
            3.使用物品建立完整的结构

#include <iostream>
#include <string>
using namespace std;

//建立最基本的单位
class Packing
{
public:
    virtual string pack() = 0;
};
class Bottle : public Packing
{
public:
    string pack()
    {
        return "Bottle";
    }
};
class Wrapper : public Packing
{
public:
    string pack()
    {
        return "Wrapper";
    }
};

//创建基本物品
class Item
{
public:
    virtual string name() = 0;
    virtual Packing *packing() = 0;
    virtual float price() = 0;
};
class Burger : public Item
{
public:
    string name()
    {
        return "";
    }
    Packing* packing()
    {
        return new Wrapper();
    }
    float price()
    {
        return 0;
    }
};
class ColdDrink : public Item
{
    string name()
    {
        return "";
    }
    Packing *packing()
    {
        return new Bottle();
    }
    float price()
    {
        return 0;
    }
};

class BurgerA : public Burger
{
public:
    string name()
    {
        return "BurgerA";
    }
    float price()
    {
        return 0.5;
    }
};
class BurgerB : public Burger
{
public:
    string name()
    {
        return "BurgerB";
    }
    float price()
    {
        return 0.7;
    }
};
class ColdDrinkA : public ColdDrink
{
    string name()
    {
        return "ColdDrinkA";
    }
    float price()
    {
        return 1.1;
    }
};
class ColdDrinkB : public ColdDrink
{
public:
    string name()
    {
        return "ColdDrinkB";
    }
    float price()
    {
        return 1.3;
    }
};

//使用创建的物品组成各种不同的产品
class Meal
{
public:
    void addItem(Item *item)
    {
        items[num++] = item;
    }
    void showItems()
    {
        int i = 0;
        for(i = 0; i < 2; ++i)
        {
            cout<<"itemName = "<<items[i]->name()<<endl;
            cout<<"itemPacking = "<<items[i]->packing()->pack()<<endl;
            cout<<"itemPrice = "<<items[i]->price()<<endl;
        }
    }
private:
    int num = 0;
    Item *items[3];
};
class MealBuilder
{
public:
    Meal* prepareVegMeal()
    {
        Meal *meal = new Meal();
        meal->addItem(new BurgerA());
        meal->addItem(new ColdDrinkA());
        return meal;
    }
    Meal* prepareNonVegMeal()
    {
        Meal *meal = new Meal();
        meal->addItem(new BurgerB());
        meal->addItem(new ColdDrinkB());
        return meal;
    }
};

int main()
{
    MealBuilder *mealBuilder = new MealBuilder();
    Meal *vegMeal = mealBuilder->prepareVegMeal();
    vegMeal->showItems();
    cout<<endl;

    Meal *vegMeal2 = mealBuilder->prepareNonVegMeal();
    vegMeal2->showItems();


    return 0;
}