设计模式<c++> (4)装饰者模式

#include <iostream>
class Beverage {    //饮料 超类
public :
    //std::string description = "未知饮料";        思考,为何这样使用成员变量不行?????????????????????????????????????????
    virtual std::string getDescription() {
        return "未知饮料";
    }
    virtual double cost() = 0;
};


class CondimentDecorator :public Beverage {//调料品 超类
public:
    virtual std::string getDescription()=0;
};



class Espresso :public Beverage {    //浓缩咖啡饮料
public:
    std::string getDescription() {
        return "浓缩咖啡饮料";
    }
    double cost() {
        return 1.99;
    }
};

class HouseBlend :public Beverage {    //家常咖啡饮料
public:
    std::string getDescription() {
        return "家常咖啡饮料";
    }

    double cost() {
        return 1.88;
    }
};

//下面定义装饰者
class Mocha :public CondimentDecorator {
public:
    Beverage *beverage;

    Mocha(Beverage *beverage) {
        this->beverage = beverage;
    }

    std::string getDescription() {
        return beverage->getDescription() + ",摩卡味";
    }

    double cost() {
        return 2.0 + beverage->cost();
    }
};

class Soy :public CondimentDecorator {
public:
    Beverage* beverage;

    Soy(Beverage* beverage) {
        this->beverage = beverage;
    }

    std::string getDescription() {
        return beverage->getDescription() + ",大豆味";
    }

    double cost() {
        return 4.0 + beverage->cost();
    }
};

class Whip :public CondimentDecorator {
public:
    Beverage* beverage;

    Whip(Beverage* beverage) {
        this->beverage = beverage;
    }

    std::string getDescription() {
        return beverage->getDescription() + ",奶油味";
    }
    double cost() {
        return 9.9 + beverage->cost();
    }
};

int  main() {
    Beverage *beverage1 = new Espresso();
    std::cout << beverage1->getDescription() <<"   价格:" <<beverage1->cost()<<std::endl;

    Beverage *beverage2 = new HouseBlend();
    std::cout << beverage2->getDescription() << "   价格:" << beverage2->cost()<<std::endl;

    beverage2 = new Whip(beverage2);
    beverage2 = new Soy(beverage2);
    beverage2 = new Mocha(beverage2);
    std::cout << beverage2->getDescription() << "   价格:" << beverage2->cost() << std::endl;
    

    delete beverage1;
    delete beverage2;
    return 0;
}

 

 

posted @ 2023-12-25 23:54  一梦、  阅读(8)  评论(0编辑  收藏  举报