c++设计模式--装饰模式

// 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;
}
 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值