一,什么是适配器模式
适配器模式(adapter),将一个类的接口转换成客户希望的另外一个接口。Adapter模式使得原本接口用不兼容而不能一起工作的那些类可以一起工作。
二,何时使用适配器模式
两个类所做的事情相同或相似,但是具有不同的接口时要使用它。使得客户端可以统一调用同一接口。接口不同时,首先不应该考虑适配器,而是应该考虑通过重构统一接口。除非是双方都不太容易修改的时候在使用适配器模式。
三,篮球翻译适配器
#include <iostream>
using namespace std;
class Player
{
public:
Player(string name)
{
mname = name;
}
virtual void Attack() = 0;
virtual void Defense() = 0;
protected: string mname;
};
class Forwards: public Player
{
public:
void Attack()
{
cout << "前锋" <<mname.c_str() << "进攻" <<endl;
}
void Defense()
{
cout << "前锋"<<mname.c_str() << "防守" <<endl;
}
};
class Center: public Player
{
public:
Center(string name) : Player(name){}
void Attack()
{
cout << "中锋"<<mname.c_str() << "进攻" <<endl;
}
void Defense()
{
cout <<"中锋"<< mname.c_str() << "防守" <<endl;
}
};
class Guards: public Player
{
public:
void Attack()
{
cout <<"后卫"<<mname.c_str() << "进攻" <<endl;
}
void Defense()
{
cout <<"后卫"<< mname.c_str() << "防守" <<endl;
}
};
class ForeignCenter
{
private:
string mname;
public:
ForeignCenter(string name)
{
mname = name;
}
void ChineseAttack()
{
cout << "中锋" << mname.c_str() << "进攻" << endl;
}
void ChineseDefense()
{
cout << "中锋" << mname.c_str() << "防守" << endl;
}
};
class Translator : public Player
{
public:
Translator(string name) : Player(name) ,ma(name){}
void Attack()
{
ma.ChineseAttack();
}
void Defense()
{
ma.ChineseDefense();
}
private:
ForeignCenter ma;
};
int main()
{
Player *p = new Center("wangcheng");
p->Attack();
Player *p1 = new Translator("yaoming");
p1->Attack();
return 0;
}