怎样做o2o网站,河南省住房与城乡建设厅网站首页,谷歌浏览器下载安装2023最新版,网站开发的技术类型有哪些装饰器模式#xff08;Decorator Pattern#xff09;是一种结构型设计模式#xff0c;允许在不修改对象代码的情况下#xff0c;动态为对象添加新功能。通过将对象包装在装饰器类中实现#xff0c;遵循开放-封闭原则#xff08;对扩展开放#xff0c;对修改封闭#xf…装饰器模式Decorator Pattern是一种结构型设计模式允许在不修改对象代码的情况下动态为对象添加新功能。通过将对象包装在装饰器类中实现遵循开放-封闭原则对扩展开放对修改封闭。
适用场景
动态扩展对象功能如为咖啡加配料、为函数加日志。需要组合多种功能。
核心组件
抽象组件定义接口。具体组件被装饰的原始对象。抽象装饰器持有一个组件对象扩展接口。具体装饰器实现具体功能的扩展。C11 实现示例
以下是一个咖啡店订单系统示例展示如何用装饰器模式为咖啡动态添加牛奶和糖。
#include iostream
#include memory
#include string// 抽象组件咖啡接口
class Coffee {
public:virtual std::string getDescription() const 0;virtual double cost() const 0;virtual ~Coffee() default;
};// 具体组件基础咖啡
class SimpleCoffee : public Coffee {
public:std::string getDescription() const override { return Simple Coffee; }double cost() const override { return 1.0; }
};// 抽象装饰器
class CoffeeDecorator : public Coffee {
protected:std::unique_ptrCoffee coffee_;
public:explicit CoffeeDecorator(std::unique_ptrCoffee coffee) : coffee_(std::move(coffee)) {}std::string getDescription() const override { return coffee_-getDescription(); }double cost() const override { return coffee_-cost(); }
};// 具体装饰器加牛奶
class MilkDecorator : public CoffeeDecorator {
public:explicit MilkDecorator(std::unique_ptrCoffee coffee) : CoffeeDecorator(std::move(coffee)) {}std::string getDescription() const override { return coffee_-getDescription() , Milk; }double cost() const override { return coffee_-cost() 0.5; }
};// 具体装饰器加糖
class SugarDecorator : public CoffeeDecorator {
public:explicit SugarDecorator(std::unique_ptrCoffee coffee) : CoffeeDecorator(std::move(coffee)) {}std::string getDescription() const override { return coffee_-getDescription() , Sugar; }double cost() const override { return coffee_-cost() 0.3; }
};// 测试
int main() {auto coffee std::make_uniqueSimpleCoffee();std::cout coffee-getDescription() : $ coffee-cost() \n;coffee std::make_uniqueMilkDecorator(std::move(coffee));std::cout coffee-getDescription() : $ coffee-cost() \n;coffee std::make_uniqueSugarDecorator(std::move(coffee));std::cout coffee-getDescription() : $ coffee-cost() \n;return 0;
}输出
Simple Coffee: $1
Simple Coffee, Milk: $1.5
Simple Coffee, Milk, Sugar: $1.8代码解析
接口Coffee定义getDescription和cost方法。基础对象SimpleCoffee实现基本咖啡功能。装饰器CoffeeDecorator通过std::unique_ptr持有Coffee对象支持递归包装。具体装饰器MilkDecorator, SugarDecorator扩展描述和价格。C11特性
std::unique_ptr管理内存防止泄漏。std::move优化对象传递。override确保虚函数正确重写。✅ 优点
灵活性运行时动态添加功能。可扩展易于新增装饰器如加巧克力。单一职责每个装饰器只负责一种功能。
⚠️ 缺点
多层装饰可能增加代码复杂性。可能有轻微性能开销调用链。
️ 注意事项
确保组件和装饰器接口一致。避免过度装饰保持代码清晰。C装饰器模式基于类的组合与Python的函数装饰器基于闭包不同。其他应用场景
日志系统为函数添加日志。权限控制为操作添加权限检查。数据流为I/O流添加加密、压缩等功能。