c++设计模式之适配器模式

/************************************************************************/
/*                             适配器模式                               */
/************************************************************************/



/*
	当两个不同接口的类需要进行通信的时候,我们可以通过定义一个适配器类
	时两者进行通信,这里举这样一个例子:姚明刚到NBA时不会说英语,此时让他现学英语
	一定是不太现实的事情,所以就可以聘请一个翻译,通过翻译与其他球员进行交流,
	翻译在这里担任的就是适配器的角色
*/





#include <IOSTREAM>


using namespace std;


class Player
{
public:
	char *name;
	Player(char *name)
	{
		this->name = name;
	}



	//进攻和防守的方法
	virtual void Attack() = 0;
	virtual void Defence() = 0;
};



//前锋
class Forwards : public Player{
public:
	Forwards(char *name) : Player(name)
	{
		this->name = name;
	}


	void Attack()
	{
		cout<<"前锋"<<name<<"进攻"<<endl;
	}


	void Defence()
	{
		cout<<"前锋"<<name<<"防守"<<endl;
	}
};



//后卫
class Guards : public Player
{
public:
	Guards(char *name) : Player(name)
	{
		this->name = name;
	}
	
	
	void Attack()
	{
		cout<<"后卫"<<name<<"进攻"<<endl;
	}
	
	
	void Defence()
	{
		cout<<"后卫"<<name<<"防守"<<endl;
	}
};




//外籍中锋(即没有继承自Player接口),由于这里的中锋是初到NBA的姚明,所以他需要一个翻译
class ForeignCencter 
{
private:
	char *name;
public:
	ForeignCencter(char *name) 
	{
		this->name = name;
	}
	
	
	void AttackInChina()
	{
		cout<<"中锋"<<name<<"进攻"<<endl;
	}
	
	
	void DefenceInChina()
	{
		cout<<"中锋"<<name<<"防守"<<endl;
	}
};



//翻译
class Translator : public Player
{
private:
	ForeignCencter *fc;

public:
	Translator(char *name):Player(name)
	{
		this->fc = new ForeignCencter("姚明");
		this->name = name;
	}


	//为姚明翻译进攻和防守
	void Attack()
	{
		//翻译成姚明能听懂的话
		fc->AttackInChina();
	}

	void Defence()
	{
		fc->DefenceInChina();
	}
	
};



void main()
{


	//教练指挥球员打球
	//前锋
	Forwards *forwards = new Forwards("詹姆斯");
	forwards->Attack();
	forwards->Defence();



	//后卫
	Guards *guards = new Guards("可比");
	guards->Attack();
	guards->Defence();


	//由于姚明听不懂英语,所以它需要翻译
	Translator *translator = new Translator("翻译");
	translator->Attack();
	translator->Defence();
}


 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值