#include <iostream> using namespace std; /* Component 类 */ class Component { public: virtual void Operation() = 0; }; /* 具体Component类,被修饰 */ class ConcreteComponent: public Component { public: void Operation() {cout<<"ConcreteComponent object's operation"<<endl;} }; /* Decorator 基类 */ class Decorator: public Component { public: void setComponent(Component *component); void Operation(); public: Component *m_component; }; void Decorator::setComponent(Component *component){ m_component = component; } void Decorator::Operation() { m_component->Operation(); } /* 具体Decorator类,修饰ConcreteComponent */ class ConcreteDecoratorA: public Decorator { public: void Operation(); }; void ConcreteDecoratorA::Operation() { Decorator::Operation(); cout<<"ConcreteDecoratorA object's operation"<<endl; } class ConcreteDecoratorB: public Decorator { public: void Operation(); }; void ConcreteDecoratorB::Operation() { Decorator::Operation(); cout<<"ConcreteDecoratorB object's operation"<<endl; } void main() { ConcreteComponent cc; ConcreteDecoratorA cdA; ConcreteDecoratorB cdB; cdA.setComponent(&cc); cdB.setComponent(&cdA); cdB.Operation(); system("pause"); }
Tips:
1. 为什么被修饰类和修饰类从同一个基类Component继承?
参考
ConcreteComponent cc;
ConcreteDecoratorA cdA;
ConcreteDecoratorB cdB;
cdA.setComponent(&cc);
cdB.setComponent(&cdA);
被修饰类ConcreteComponent和修饰类ConcreteDecorator都可以被叠加修饰.
2. 什么情况下使用修饰模式?
装饰模式是一种为已有功能动态地添加更多功能的方式。 同样的扩展功能还有两个方法:
1)修改当前类,添加字段和方法
2)创建新的子类
第一种方法不符合开闭原则和单一职责原则,会使得当前类越来越复杂。
当新加入的功能仅仅是为了满足某种特定情况才会被执行时,装饰模式更加适合,它把每个要装饰的功能放在单独的类中,让这个类来包装主类。用户可以有选择的,按顺序的扩展功能。