<aside> 💡

装饰模式(Decorator):动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式闭生成子类更加灵活

</aside>

结构图

image.png

优缺点

优点

应用场景

题目

https://kamacoder.com/problempage.php?pid=1086

#include <iostream>
using namespace std;

// 抽象基类(Component类)
class Coffee{
public:
    virtual void brew() = 0;
    virtual ~Coffee(){};
};

// 具体的黑咖啡被装饰类
class BlackCoffee: public Coffee{
public:
    void brew() override {
        cout << "Brewing Black Coffee" << endl;
    }
};

// 具体的拿铁被装饰类
class LatteCoffee: public Coffee{
public:
    void brew() override {
        cout << "Brewing Latte" << endl;
    }
};

// 装饰器抽象类(Decorator类)
class Decorator: public Coffee{
public:
    void setCoffee(Coffee* coffee){
        this->coffee = coffee;
    }
    // 装饰器类的brew()方法嵌套具体组件类的brew()方法,形成了一个执行链
    void brew() override {
        coffee->brew();
    }
protected:
    Coffee* coffee;
};

// 牛奶装饰器类
class MilkDecorator: public Decorator{
public:
    void brew() override {
        coffee->brew();
        cout << "Adding Milk" << endl;
    }
};

// 砂糖装饰器类
class SugarDecorator: public Decorator{
public:
    void brew() override {
        coffee->brew();
        cout << "Adding Sugar" << endl;
    }
};

int main(){
    int coffeeType, decoratorType;
    while(cin >> coffeeType >> decoratorType){
        Coffee* coffee = nullptr;
        Decorator* decorator = nullptr;

        // 创建被装饰对象(咖啡)
        switch(coffeeType){
        case 1:
            coffee = new BlackCoffee();
            break;
        case 2:
            coffee = new LatteCoffee();
            break;
        }

        // 创建装饰(调料)
        switch(decoratorType){
        case 1:
            decorator = new MilkDecorator();
            break;
        case 2:
            decorator = new SugarDecorator();
            break;
        }

				// 调用装饰器对象
        // 沿着执行链一层层地对被装饰物进行装饰
        decorator->setCoffee(coffee);
        decorator->brew();

        delete coffee;
        delete decorator;
    }
    return 0;
}