设计模式读书笔记:Decorator(装饰)
2015-07-10 16:28:02
意图:
动态地给一个对象添加一些额外的职责。就增加功能来说,Decorator模式相比生成子类更为灵活。
结构图:来自 《23种设计模式 - 郗晓勇》
实现:https://github.com/panshiqu/patterns/tree/master/Decorator
Component
namespace NS_DECORATOR {
class Component {
public:
Component() {}
virtual ~Component() {}
virtual void operation(void) = 0;
};
} /* namespace NS_DECORATOR */
ConcreteComponent
#include "Component.h"
#include <iostream>
namespace NS_DECORATOR {
class ConcreteComponent : public Component
{
public:
ConcreteComponent() {}
virtual ~ConcreteComponent() {}
virtual void operation(void)
{
std::cout << "ConcreteComponent" << std::endl;
}
};
} /* namespace NS_DECORATOR */
Decorator
#include "Component.h"
namespace NS_DECORATOR {
class Decorator : public Component
{
public:
Decorator(Component *component) : _component(component) {}
virtual ~Decorator() {}
virtual void operation(void)
{
_component->operation();
}
private:
Component *_component;
};
} /* namespace NS_DECORATOR */
ConcreteDecoratorA
#include "Decorator.h"
#include <iostream>
namespace NS_DECORATOR {
class ConcreteDecoratorA : public Decorator
{
public:
ConcreteDecoratorA(Component *component) : Decorator(component) {}
virtual ~ConcreteDecoratorA() {}
virtual void operation(void)
{
Decorator::operation();
addBehavior();
}
void addBehavior(void)
{
std::cout << "Jump" << std::endl;
}
};
} /* namespace NS_DECORATOR */
ConcreteDecoratorB
#include "Decorator.h"
#include <iostream>
namespace NS_DECORATOR {
class ConcreteDecoratorB : public Decorator
{
public:
ConcreteDecoratorB(Component *component) : Decorator(component) {}
virtual ~ConcreteDecoratorB() {}
virtual void operation(void)
{
Decorator::operation();
addBehavior();
}
void addBehavior(void)
{
std::cout << "Move" << std::endl;
}
};
} /* namespace NS_DECORATOR */
main
#include "Decorator/ConcreteComponent.h"
#include "Decorator/ConcreteDecoratorA.h"
#include "Decorator/ConcreteDecoratorB.h"
using namespace NS_DECORATOR;
using namespace std;
int main(void)
{
ConcreteComponent cc;
cc.operation();
cout << "----------" << endl;
ConcreteDecoratorA cda(&cc);
cda.operation();
cout << "----------" << endl;
ConcreteDecoratorB cdb(&cda);
cdb.operation();
}
附加: