装饰模式:动态的给一个对象添加一些额外的职能。
网上有个说法感觉比较形象(http://zhousenbiao.com/Design-Patterns/decorator.html):
所谓装饰,就是一些对象给主体对象做陪衬。这是我的理解。好比说我的办公桌,需要电脑、电话、文件夹、盆栽等作为装饰。那么,办公桌就是一个主体对象,电脑、电话等装饰品就是那些做陪衬的对象。这些办公用品准备好了,该怎么摆放到办公桌上呢?可以有多种方案。而且,我可以随时往办公桌上增加一支签字笔,增加一枚公章等等。
目前,可归纳如下:
A主体对象:办公桌
B装饰者:电脑、电话、文件夹、盆栽、签字笔、公章
C装饰者可以装饰主体对象,即B可以装饰A
什么是装饰模式?一个标准的定义是:动态地将责任附加到对象上。若要扩展功能,装饰者提供了比基础更有弹性的替代方案。
根据我的理解,装饰模式可以这样定义:能够动态地为对象添加功能,同时不会对类进行修改。
网上还有篇装饰者模式总结得比较好的:http://www.cnblogs.com/god_bless_you/archive/2010/06/10/1755212.html
好了,不多说。C++代码如下:
#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;
class Person
{
public:
Person(){}
~Person(){}
Person(std::string name)
{
m_strName = name;
}
virtual void Show()
{
cout<<"装扮的"<<m_strName<<endl;
}
private:
std::string m_strName;
};
class Finery: public Person
{
public:
Finery(){}
~Finery(){}
void Decorate(Person* compent)
{
m_component = compent;
}
void Show()
{
if (m_component)
{
m_component->Show();
}
}
private:
Person* m_component;
};
class TShirt: public Finery
{
public:
TShirt(){}
~TShirt(){}
void Show()
{
cout<<"T恤 ";
Finery::Show();
}
};
class Sneakers: public Finery
{
public:
Sneakers(){}
~Sneakers(){}
void Show()
{
cout<<"破球鞋 ";
Finery::Show();
}
};
class Suit : public Finery
{
public:
Suit(){}
~Suit(){}
void Show()
{
cout<<"西装 ";
Finery::Show();
}
};
class Tie : public Finery
{
public:
Tie(){}
~Tie(){}
void Show()
{
cout<<"领带 ";
Finery::Show();
}
};
int _tmain(int argc, _TCHAR* argv[])
{
Person* person = new Person("小菜");
cout<<"第一种装扮:"<<endl;
TShirt* tshirt = new TShirt();
Tie* tie = new Tie();
Suit* suit = new Suit();
tshirt->Decorate(person);
tie->Decorate(tshirt);
suit->Decorate(tie);
suit->Show();
return 0;
}
代码很简单,在这里只是作为学习它的一个记录!