目录
动态地给一个对象添加一些额外的职责。就增加功能来说,Decorator模式相比生成子类更为灵活。
定义一个对象接口,可以给这些对象动态地添加职责。
定义一个对象,可以给这个对象添加一些职责。
维持一个指向Component对象的指针,并定义一个与Component接口一致的接口。
向组件添加职责。
- #include
- using namespace std;
-
- class Component {
- public:
- virtual void Operation() = 0;
- };
-
- class ConcreteComponent : public Component{
- public:
- virtual void Operation() {
- cout << "ConcreteComponent" << endl;
- }
- };
-
- class Decorator : public Component {
- public:
- Decorator(Component* tempComponent) :component(tempComponent) {}
- virtual void Operation() {
- component->Operation();
- }
- private:
- Component* component;
- };
-
- class ConcreteDecoratorA : public Decorator {
- public:
- ConcreteDecoratorA(Component* tempComponent) :Decorator(tempComponent) {}
- virtual void Operation() {
- Decorator::Operation();
- cout << "ConcreteDecoratorA" << endl;
- }
- };
-
- class ConcreteDecoratorB : public Decorator {
- public:
- ConcreteDecoratorB(Component* tempComponent) :Decorator(tempComponent) {}
- virtual void Operation() {
- Decorator::Operation();
- cout << "ConcreteDecoratorB" << endl;
- }
- };
-
- int main() {
- Component* component = new ConcreteComponent;
- component->Operation();
-
- Component* componentA = new ConcreteDecoratorA(component);
- componentA->Operation();
-
- Component* componentB = new ConcreteDecoratorB(component);
- componentB->Operation();
-
- return 0;
- }