意图:
动态的给一个对象添加一个额外的职责
适用性:
1在不影响其它对象的情况下,以动态透明的方式给单个对象添加职责
2处理可以撤销的职责
3当不能采用生成子类的方法进行扩充时
效果:
1比静态继承更灵活,用添加和分离的方法,用装饰在运行时刻增加和删除职责,而且使用Decorator很容易重复添加一个特性
2避免在层次结构高层的类有太多的特征
3Decorator与其它Component不一样,使用装饰不应该依赖对象标识
4有许多小对象
实现:
1接口的一致性 装饰对象的接口必须与它所装饰的Component接口一致,因此所有ConcreteDecorator必须有一个公共的父类。
2省略抽象的Decorator类,当你仅需要添加一个职责时
3 保持Component类的简单性 为了保持接口一致性,组件和装饰必须有共同的父类
4改变对象外壳和内核(Strategy模式用于修改内核,Decorator模式用于修改外壳)
Decorator.h
- #include <iostream>
- using namespace std;
- class VisualComponent
- {
- public:
- VisualComponent(){cout<<"VisualComponent is created"<<endl;}
- virtual void Draw(){cout<<"Draw on VisualComponent"<<endl;}
- virtual void Resize(){cout<<"Resize on VisualComponent"<<endl;}
- };
- class Window:public VisualComponent
- {
- public:
- Window(){cout<<"Window is created"<<endl;}
- void SetContents(VisualComponent *)
- {
- cout<<"Set Contents on an Visual Component "<<endl;
- }
- };
- class TextView:public VisualComponent
- {
- public:
- TextView(){cout<<"TextView is created"<<endl;}
- };
- class Decorator:public VisualComponent
- {
- public:
- Decorator(VisualComponent* x){_component=x;cout<<"Decorator is added"<<endl;}
- virtual void Draw(){cout<<"Decorate on Component"<<endl;}
- virtual void Resize(){cout<<"Resize on Component"<<endl;}
- private:
- VisualComponent* _component;
- };
- class BorderDecorator:public Decorator
- {
- public:
- BorderDecorator(VisualComponent* x,int borderWidth):Decorator(x)
- {
- _width = borderWidth;
- cout<<"BorderDecorator is added"<<endl;
- }
- virtual void Draw()
- {Decorator::Draw();
- DrawBorder();}
- private:
- void DrawBorder()
- {cout<<"Draw border on Component,the width is "<<_width<<endl;}
- int _width;
- };
main.cpp
- #include <iostream>
- using namespace std;
- #include "Decorator.h"
- int main()
- {
- Window a;
- TextView b;
- TextView* c=&b;
- a.SetContents(new BorderDecorator(new Decorator(c),1));
- return 0;
- }