标签:
1.意图
动态地给一个对象添加一些额外的职责。就增加功能来说,Decorator模式相比生成子类更为灵活。
2.别名
包装器 Wrapper.
3.动机
给某个对象而不是整个类添加一些功能。一个较为灵活的方式时将组件嵌入另一个对象中。
4.适用性
5.结构
6.代码实例
#include <memory> class Component { public: virtual void Operation()=0; }; class ConcreteComponent : public Component { public: void Operation(); }; class Decorator : public Component { public: virtual void Operation(); void SetComponent(std::shared_ptr<Component> pComponent); protected: std::shared_ptr<Component> m_pComponent; }; class ConcreteDecoratorA : public Decorator { public: void Operation(); void OtherBehavior(); }; class ConcreteDecoratorB : public Decorator { public: void Operation(); void OtherBehavior(); };
#include "Component.h" #include <iostream> void ConcreteComponent::Operation() { std::cout << "ConcreteComponent Operation executed" <<std::endl; } void Decorator::Operation() { m_pComponent->Operation(); } void Decorator::SetComponent(std::shared_ptr<Component> pComponent) { m_pComponent = pComponent; } void ConcreteDecoratorA::Operation() { Decorator::Operation(); OtherBehavior(); } void ConcreteDecoratorA::OtherBehavior() { std::cout<<"ConceteDecoratorA OtherBehavior executed" << std::endl; } void ConcreteDecoratorB::Operation() { Decorator::Operation(); OtherBehavior(); } void ConcreteDecoratorB::OtherBehavior() { std::cout<<"ConcreteDecoratorB OtherBehavior executed" << std::endl; }
#include "Component.h" int main() { std::shared_ptr<Component> pComponent(new ConcreteComponent); std::shared_ptr<Decorator> pDecoratorA(new ConcreteDecoratorA); pDecoratorA->SetComponent(pComponent); pDecoratorA->Operation(); std::shared_ptr<Decorator> pDecoratorB(new ConcreteDecoratorB); pDecoratorB->SetComponent(pComponent); pDecoratorB->Operation(); while(1); }
7.测试结果
8.效果
标签:
原文地址:http://www.cnblogs.com/mgp200866130/p/5539923.html