DesignPatterns/c++/decorator.cc
2025-07-10 22:26:33 +08:00

37 lines
780 B
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* @name 装饰器模式
* @brief: 动态添加职责
* @note 场景:流处理(加密/压缩装饰、GUI 组件增强
*/
class Coffee {
public:
virtual double cost() = 0;
};
class SimpleCoffee : public Coffee {
public:
double cost() override { return 6.9; }
};
class CoffeeDecorator : public Coffee {
protected:
Coffee* coffee;
public:
CoffeeDecorator(Coffee* c) : coffee(c) {}
};
class MilkDecorator : public CoffeeDecorator {
public:
MilkDecorator(Coffee* c) : CoffeeDecorator(c) {}
double cost() override {
return coffee->cost() + 0.5; // 增加牛奶费用
}
};
// 使用
int main()
{
Coffee* coffee = new SimpleCoffee();
coffee = new MilkDecorator(coffee); // 动态装饰
coffee->cost(); // 基础 + 牛奶
}