// DecoratorPattern.cpp : 定义控制台应用程序的入口点。
//通过此例程了解设计模式里的“装饰模式”
//装饰模式:动态地给一个对象添加额外的职责,就增加功能来说,装饰模式比生成子类更加灵活
//下面利用游戏玩家升级后的装扮解释装扮模式
#include "stdafx.h"
#include <string>
#include <process.h>
#include <iostream>
using namespace std;
//游戏玩家类
class CPlayer
{
public:
CPlayer()
{
}
CPlayer(const string Name)
{
this->m_name=Name;
}
virtual void Show() const
{
cout<<"玩家---"<<m_name<<endl<<endl;
}
private:
string m_name;
};
//装扮基类,继承自玩家类,如果不定义Show方法,缺省实现为基类的Show方法,
class CFinery:public CPlayer
{
public:
void Decorate(CPlayer *player)
{
this->m_player=player;
}
void Show() const
{
if (m_player!=NULL)
{
m_player->Show();
}
}
private:
CPlayer *m_player;
};
//具体装扮类,继承自装扮类,所以缺省实现有Decorate方法和Show方法
class CTShirts:public CFinery
{
public:
void Show() const
{
cout<<"T恤"<<endl;
CFinery::Show();
}
};
class CSneakers:public CFinery
{
public:
void Show() const
{
cout<<"长靴"<<endl;
CFinery::Show();
}
};
class CSuit:public CFinery
{
public:
void Show() const
{
cout<<"风衣"<<endl;
CFinery::Show();
}
};
class CSmallshoes:public CFinery
{
public:
void Show() const
{
cout<<"短靴"<<endl;
CFinery::Show();
}
};
int _tmain(int argc, _TCHAR* argv[])
{
cout<<"-----------装扮模式测试案例------------------"<<endl<<endl;
CPlayer *p_player=new CPlayer("鬼剑士");
cout<<"游戏玩家角色装扮---1"<<endl;
CTShirts *pTshirts=new CTShirts();
CSmallshoes *pSmallShoes=new CSmallshoes();
pTshirts->Decorate(p_player);
pSmallShoes->Decorate(pTshirts);
pSmallShoes->Show();
cout<<endl<<endl;
cout<<"游戏玩家角色装扮---2"<<endl;
CSuit *pSuit=new CSuit();
CSneakers *pSneakers=new CSneakers();
pSuit->Decorate(p_player);
pSneakers->Decorate(pSuit);
pSneakers->Show();
system("pause");
return 0;
}