您的位置:首页 > 其它

设计模式之适配器模式学习

2012-05-22 21:36 288 查看
适配器模式:将一个类的接口转换成客户希望的另外一个接口,使原本由于接口不兼容不能一起工作的那些类可以一起工作。适配器就是是一个东西适合另外一个东西。



在软件开发中,系统的数据和行为都正确,但接口不符时,应该考虑适配器模式,目的是使控制范围之外的一个原有对象与某个接口匹配。适配器模式主要应用于希望复用一些现存的类,但是接口又与复用环境要求的不一致的情况。也就是说,在想使用一个已存在的类,但它的接口与要求不同时就应该考虑适配器模式,客户端同一调用统一接口,这样就可以更简单、更直接、更紧凑。
代码结构图




#include<iostream>
#include<string>
using namespace std;
class Player
{
public:
	string name;
public:
	Player(string s)
		:name(s)
	{

	}
	virtual void attack()=0;
	virtual void defence()=0;
};
class Forward:public Player
{
public:
	Forward(string s)
		:Player(s)
	{

	}
	virtual void attack()
	{
		cout<<"前锋"<<name<<"进攻!"<<endl;
	}
	virtual void defence()
	{
		cout<<"前锋"<<name<<"防守!"<<endl;
	}
};
class Center:public Player
{
public:
	Center(string s)
		:Player(s)
	{

	}
	virtual void attack()
	{
		cout<<"中锋"<<name<<"进攻!"<<endl;
	}
	virtual void defence()
	{
		cout<<"中锋"<<name<<"防守!"<<endl;
	}
};
class Guard:public Player
{
public:
	Guard(string s)
		:Player(s)
	{

	}
	virtual void attack()
	{
		cout<<"后卫"<<name<<"进攻!"<<endl;
	}
	virtual void defence()
	{
		cout<<"后卫"<<name<<"防守!"<<endl;
	}
};
class ChinesePlayer
{
public:
	string name;
public:
	ChinesePlayer(string s)
		:name(s)
	{

	}
	void jingong()
	{
		cout<<"中国球员"<<name<<"进攻"<<endl;
	}
	void fangshou()
	{
		cout<<"中国球员"<<name<<"防守"<<endl;
	}

};
class Translator:public Player
{
public:
	ChinesePlayer *chp;
public:
	Translator(string s)
		:Player(s)
	{
		chp=new ChinesePlayer(s);
	}
	virtual void attack()
	{
		chp->jingong();
	}
	virtual void defence()
	{
		chp->fangshou();
	}
};
int main(int argc,char**argv)
{
	Forward *fd=new Forward("路易斯");
	Guard *gd=new Guard("特雷西");
	Center*ct=new Center("迪肯贝");
	Translator *tl=new Translator("姚明");

	fd->attack();
	fd->defence();

	ct->attack();
	ct->defence();

	tl->attack();
	tl->defence();
	gd->attack();
	gd->defence();

	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: