用代码和UML图化解设计模式之《装饰模式》
这个模式看了两次,因为我有点不太理解,其实到现在也不太理解。
通过写代码,自我理解就是把对象重新装饰了一遍。通过继承同一个基类。而不用添加额外的类了。。。。
上图吧
通过修饰类达到我们想要的效果。修饰类通常初始化了基类。
[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;
}
补充:软件开发 , C++ ,