全国 【切换城市】欢迎您来到装修百科!
关注我们
我要装修

09-装饰模式(Decorator)(装饰模式的调用)

发布:2024-09-08 浏览:25

核心提示:意图装饰模式是一种结构型设计模式。它动态地给一个对象添加一些额外的职责。就增加功能来说,装饰模式相比生成子类更为灵活。结构装饰模式结构图装饰模式例图代码示例#include <iostream> #include <memory> #include <string>/// 接口 // 可见组建 class VisualComponent { public:using Ptr = std::shared_ptr<VisualComponent>;VisualC

意图装饰模式是一种结构型设计模式。
它动态地给一个对象添加一些额外的职责。
就增加功能来说,装饰模式相比生成子类更为灵活。
结构装饰模式结构图装饰模式例图代码示例#include <iostream>#include <memory>#include <string>/// 接口// 可见组建class VisualComponent {public: using Ptr = std::shared_ptr<VisualComponent>; VisualComponent() {} virtual ~VisualComponent() {} virtual void Draw() = 0;};// 文本视口class TextView : public VisualComponent {public: TextView() : VisualComponent() {} virtual ~TextView() {} void Draw() override { std::cout << "Draw TextView!" << std::endl; }};// 装饰器class Decorator : public VisualComponent {public: Decorator(VisualComponent* vc) : VisualComponent(), _vc(vc) {} virtual ~Decorator() {} void Draw() override { if (_vc) {_vc->Draw();} };private: VisualComponent* _vc = nullptr;};// 滚动条装饰器class ScrollDecorator : public Decorator {public: ScrollDecorator(VisualComponent* vc) : Decorator(vc) {} virtual ~ScrollDecorator() {} void Draw() override { std::cout << ">>>" << std::endl; Decorator::Draw(); ScrollTo(); std::cout << "<<<" << std::endl; }protected: void ScrollTo() { std::cout << "Draw Scroll!" << std::endl; }};// 边框装饰器class BorderDecorator : public Decorator {public: BorderDecorator(VisualComponent* vc) : Decorator(vc) {} virtual ~BorderDecorator() {} void Draw() override { std::cout << ">>>" << std::endl; Decorator::Draw(); DrawBorder(); std::cout << "<<<" << std::endl; }protected: void DrawBorder() { std::cout << "Draw Border!" << std::endl; }};// use it!int main(int argc, char* argv[]) { VisualComponent::Ptr textView(new TextView()); // 滚动条装饰 Decorator::Ptr scrollDecorator(new ScrollDecorator(textView.get())); scrollDecorator->Draw(); // 边框装饰 Decorator::Ptr borderDecorator(new BorderDecorator(textView.get())); borderDecorator->Draw(); return 0;}运行结果适用性在不影响其他对象的情况下,以动态、透明的方式给单个对象添加职责;处理那些可以撤销的职责;当不能采用生成子类的方法进行扩充时;这存在两种情况:一种情况是,可能有大量独立的扩展,为支持每一种组合将产生大量的子类,使得子类数目呈爆炸性增长;另一种情况可能是因为类定义被隐藏,或类定义不能用于生成子类(比如上述例子中,TextView不对外暴露,用户只能通过参数创建TextView实例时)。

  • 收藏

分享给我的朋友们:

上一篇:设计模式:结构类之装饰模式(Decorator)意图场景和代码示例(装饰设计模式java) 下一篇:天燃气热水器选购注意什么 天燃气热水器的禁忌是什么

一键免费领取报价清单 专享六大服务礼包

装修全程保障

免费户型设计+免费装修报价

已有312290人领取

关键字: 装修百科 装修咨询 装修预算表

发布招标得免费设计

申请装修立省30%

更多装修专区

点击排行