美文网首页
建造者模式

建造者模式

作者: 大啸 | 来源:发表于2019-03-24 16:25 被阅读0次

    #include <iostream>

    #include <string>

    #include <vector>

    using namespace std;

    class Packing {

    public:

    virtual string pack() {

    return "";

    }

    };

    class Wraper : public Packing {

    public:

    string pack() {

    return "纸包装的食物";

    }

    };

    class Botton : public Packing{

    public:

    string pack() {

    return "杯子包装的食物";

    }

    };

    class Item {

    public:

    virtual string name() = 0;

    virtual Packing *packing() = 0;

    virtual float price() = 0;

    };

    class Burger : public Item {

    public:

    float price() {

    return 17.5;

    }

    Packing *packing() {

    Packing *pack = new Wraper();

    return pack;

    }

    string name() {

    string n = "这是堡";

    return n;

    }

    };

    class Drank : public Item {

    public:

    float price() {

    return 12.5;

    }

    Packing *packing() {

    Packing *pack = new Botton();

    return pack;

    }

    string name() {

    string n = "这是饮料";

    return n;

    }

    };

    class VerBurger : public Burger {

    public:

    float price() {

    return 10.5;

    }

    string name() {

    string n = "田园果蔬堡";

    return n;

    }

    };

    class ChenBurger : public Burger {

    public:

    float price() {

    return 20.5;

    }

    string name() {

    string n = "奥尔良烤鸡腿堡";

    return n;

    }

    };

    class CocaColo : public Drank {

    float price() {

    return 15.5;

    }

    string name() {

    string n = "可口可乐";

    return n;

    }

    };

    class Mail {

    public:

    vector<Item*> mailList;

    void Order() {

    int type = 0;

    Item *it = nullptr;

    cout << "输入1-3点餐,其他数字完成点餐^_^" << endl;

    while (type != 100) {

    cin >> type;

    switch (type) {

    case 1: it = new VerBurger(); mailList.push_back(it); break;

    case 2: it = new ChenBurger(); mailList.push_back(it); break;

    case 3: it = new CocaColo(); mailList.push_back(it); break;

    default: type = 100; break;

    }

    }

    }

    void showDetal() {

    float sum = 0.0;

    for (int i = 0; i != mailList.size(); i++) {

    sum += mailList[i]->price();

    cout << mailList[i]->packing()->pack() << "包装的" << mailList[i]->name() << endl;

    }

    cout << "价值:" << sum << "元" << endl;

    }

    };

    int main()

    {

    Mail *order = new Mail();

    order->Order();

    order->showDetal();

        std::cout << "Hello World!\n";

    }

    相关文章

      网友评论

          本文标题:建造者模式

          本文链接:https://www.haomeiwen.com/subject/hkvuvqtx.html