设计模式之适配器模式
【定义】Adapter,将一个类的接口转换成客户希望的另外一个接口。Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
【场景】姚明在NBA打球,他和火箭的其他队友打得都是篮球,但首先姚明英文很差,为了让他和其他球员有效的沟通,这时可以为他实现一个语言的适配器,也就是请一个翻译,在适配器的帮助下,姚明即能使出球技也能正常英文沟通,表现的和其他美国球员一样。
【UML】
【CODE】
#include <iostream>
using namespace std;
class Player
{
public:
virtual void attack() = 0;
virtual void defense() = 0;
};
//前锋
class Forward : public Player
{
public:
virtual void attack()
{
cout<<"Forward attack"<<endl;
}
virtual void defense()
{
cout<<"Forward defense"<<endl;
}
};
//中锋
class Center : public Player
{
public:
virtual void attack()
{
cout<<"Center attack"<<endl;
}
virtual void defense()
{
cout<<"Center defense"<<endl;
}
};
//后卫
class Guard : public Player
{
public:
virtual void attack()
{
cout<<"Guard attack"<<endl;
}
virtual void defense()
{
cout<<"Guard defense"<<endl;
}
};
//外籍球员
class ForeignPlayer
{
private:
public:
void foreign_attack()
{
cout<<"ForeignPlayer 进攻"<<endl;
}
void foreign_defense()
{
cout<<"ForeignPlayer 防守"<<endl;
}
};
//翻译
class Translator : public Player
{
private:
ForeignPlayer* foreign;
public:
void set_foreign(ForeignPlayer* f)
{
foreign = f;
}
virtual void attack()
{
cout<<"Translator attack"<<endl;
foreign->foreign_attack();
}
virtual void defense()
{
cout<<"Translator defense"<<endl;
foreign->foreign_defense();
}
};
int main()
{
Player* center = new Center();
center->attack();
ForeignPlayer* p = new ForeignPlayer();
Translator* translator = new Translator();
translator->set_foreign(p);
translator->attack();
delete center;
delete translator;
delete p;
return 0;
}
不积跬步无以至千里,不积小流无以成江河。