一、意图:
动态的给对象添加二外的职责,相比于生成子类来说更为灵活;
二、类图:
三、组成元素:
Component:对象接口,可以给这些对象动态添加功能;
ConcreteComponent:具体对象;
Decorator:修饰接口;
ConcreteDecorator:向组件添加功能;
四、实现代码:
#include <iostream> using namespace std; class Component { public: virtual void Operation()=0; }; class ConcreteComponent:public Component { public: void Operation() { cout<<"I'm Component"; } }; class Decorator:public Component { public: Decorator(){} Decorator(Component* com) { component=com; } virtual void Operation() { component->Operation(); } protected: Component* component; }; class ConcreteDecoratorB:public Decorator { public: ConcreteDecoratorB(Component* pComponent):Decorator(pComponent){} void Operation() { cout<<"["; /*component->Operation();*/ //根据多态原理,调用相应的Operation Decorator::Operation(); cout<<"]"; } }; void main() { Component* pComponent=new ConcreteComponent; Decorator* pDecorator=new ConcreteDecoratorB(pComponent); pDecorator->Operation(); cout<<endl; Decorator* p1=new ConcreteDecoratorB(pDecorator); p1->Operation(); cout<<endl; Decorator* p2=new ConcreteDecoratorB(p1); p2->Operation(); cout<<endl; }