這個模式看了兩次,因為我有點不太理解,其實到現在也不太理解。
通過寫代碼,自我理解就是把對象重新裝飾了一遍。通過繼承同一個基類。而不用添加額外的類了。。。。
上圖吧
通過修飾類達到我們想要的效果。修飾類通常初始化了基類。
[cpp]
// Decorator.cpp : 定義控制台應用程序的入口點。
//************************************************************************/
/* @filename Decorator.cpp
@author wallwind
@createtime 2012/10/29 22:42
@function 命令模式
@email */
/************************************************************************/
#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* twidget = new TextField(2,3);
Widget *sd = new ScrollDecorator(twidget);
Widget *br = new BorderDecorator(twidget);
sd->show();
br->show();
return 0;
}