自我理解就是把對象重新裝飾了一遍。通過繼承同一個基類。而不用添加額外的類了。。。。
上圖吧
通過修飾類達到我們想要的效果。修飾類通常初始化了基類。
- // Decorator.cpp : 定義控制檯應用程序的入口點。
- //************************************************************************/
- /* @filename Decorator.cpp
- @author wallwind
- @createtime 2012/10/29 22:42
- @function 命令模式
- @email [email protected]
- */
- /************************************************************************/
- #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;
- }