自我理解就是把对象重新装饰了一遍。通过继承同一个基类。而不用添加额外的类了。。。。
上图吧
通过修饰类达到我们想要的效果。修饰类通常初始化了基类。
- // Decorator.cpp : 定义控制台应用程序的入口点。
- //************************************************************************/
- /* @filename Decorator.cpp
- @author wallwind
- @createtime 2012/10/29 22:42
- @function 命令模式
- @email wochenglin@qq.com
- */
- /************************************************************************/
- #include "stdafx.h"
- #include <iostream>
- using namespace std;
- class Widget
- {
- public:
- Widget(){}
- virtual ~Widget(){}
- virtual void show()=0;
- };
- class TextField:public Widget
- {
- public:
- TextField(int ix,int iy)
- :x(ix),y(iy)
- {
- }
- ~TextField(){}
- void show()
- {
- cout<<"x:"<<x<<endl;
- cout<<"y:"<<y<<endl;
- }
- private:
- int x;
- int y;
- };
- class Decorator:public Widget
- {
- public:
- Decorator(Widget* widget)
- :m_widget(widget)
- {}
- virtual ~Decorator()
- {
- delete m_widget;
- }
- void show()
- {
- m_widget->show();
- cout<<"Decorator:show()"<<endl;
- }
- private:
- Widget* m_widget;
- };
- class BorderDecorator :public Decorator
- {
- public:
- BorderDecorator(Widget* widget)
- :Decorator(widget)
- {
- }
- void show()
- {
- Decorator::show();
- cout<<"BorderDecorator:show()"<<endl;
- }
- };
- class ScrollDecorator :public Decorator
- {
- public:
- ScrollDecorator(Widget* widget)
- :Decorator(widget)
- {
- }
- void show()
- {
- Decorator::show();
- cout<<"ScrollDecorator:show()"<<endl;
- }
- };
- int _tmain(int argc, _TCHAR* argv[])
- {
- Widget* aWidget = new BorderDecorator(
- new BorderDecorator(
- new ScrollDecorator(
- new TextField( 80, 24 ))));</p><p> aWidget->show();
- return 0;
- }