适配器模式(Adapter):将一个类的接口转换成客户希望的另外一个接口。它使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
适配器模式主要用在希望复用一些现存的类,但是接口又与复用环境要求不一致的情况。
比如:在一个球队中有本土球员和外籍球员。由于语言不通,所以需要一个翻译作为适配器,让外籍球员与本土球员可以一起工作。
UML:
//抽象球员类
class Player {
protected:
string m_name;
public:
Player(string name):m_name(name){}
virtual void Attack() = 0;
virtual void Defense() = 0;
};
//前锋类
class Forward :public Player {
public:
Forward(string name) :Player(name) {}
void Attack()
{
cout << m_name << "进攻 ";
}
void Defense()
{
cout << m_name << "防守 " << endl;
}
};
//外籍球员类
class ForeignPlayer{
private:
string m_name;
public:
void SetName(string name)
{
m_name = name;
}
void Attack2() //外籍球员进攻防守方式不同
{
cout << m_name << "进攻 ";
}
void Defense2()
{
cout << m_name << "防守 " << endl;
}
};
//翻译者
class Translator :public Player {
private:
ForeignPlayer *player = new ForeignPlayer(); //外籍球员对象
public:
Translator(string name): Player(name)
{
player->SetName(name);
}
void Attack()
{
player->Attack2();//调用外籍球员的方法
}
void Defense()
{
player->Defense2();
}
};
int main()
{
Player *A = new Forward("qianfeng");
A->Attack();
A->Defense();
Player *B = new Translator("yaoming");
B->Attack();
B->Defense();
system("pause");
return 0;
}