装饰模式是在不必改变原类文件和使用继承的情况下,动态地扩展一个对象的功能。它是通过创建一个包装对象,也就是装饰来包裹真实的对象。
#pragma once
#include <iostream>
using namespace std;
struct IComponent
{
virtual void operation() = 0;
};
class ConcreteComponent :public IComponent
{
public:
void operation()
{
cout << "call ConcreteComponent operation" << endl;
}
};
class Decorator :public IComponent
{
public:
Decorator()
:_comp(nullptr)
{}
virtual ~Decorator()
{
delete _comp;
_comp = nullptr;
}
virtual void operation()
{
_comp->operation();
cout << "call Decorator operation" << endl;
}
virtual void setComponent(IComponent* comp)
{
_comp = comp;
}
protected:
IComponent* _comp;
};
class ConcreteDecoratorA :public Decorator
{
public:
virtual void operation()
{
_comp->operation();
addedState();
cout << "call ConcreteDecoratorA operation" << endl;
}
virtual void addedState()
{
cout << "call ConcreteDecoratorA addedState" << endl;
}
};
class ConcreteDecoratorB :public Decorator
{
public:
virtual void operation()
{
_comp->operation();
addedBehavior();
cout << "call ConcreteDecoratorB operation" << endl;
}
virtual void addedBehavior()
{
cout << "call ConcreteDecoratorB addedBehavior" << endl;
}
};
void decoratorTest()
{
IComponent *concreteComp = new ConcreteComponent;
Decorator *concreteDectA = new ConcreteDecoratorA;
concreteDectA->setComponent(concreteComp);
concreteDectA->operation();
Decorator *concreteDectB = new ConcreteDecoratorB;
concreteDectB->setComponent(concreteDectA);
concreteDectB->operation();
}