適配器模式
前序
姚明,大家都認識吧。在他剛去NBA的時候,什么都聽不懂,必須在旁邊配個翻譯,否則就無法聽懂教練在說什么。這也正符合了設計模式中的一種模式:適配器模式。
適配器模式
將一個類的接口轉換成客戶希望的另外一個接口。適配器模式使得原本由于接口不兼容而不能一起工作的那些類可以一起工作。
實現方式(UML類圖)

實現代碼
#include <stdio.h>
// 球員
class Player
{
public:
Player(char* _name) : name(_name){}
virtual void Attack()=0;
virtual void Defense()=0;
char* name;
};
// 前鋒
class Forwards : public Player
{
public:
Forwards(char* name) : Player(name){}
virtual void Attack()
{
printf("前鋒 %s 進攻\n", name);
}
virtual void Defense()
{
printf("前鋒 %s 防守\n", name);
}
};
// 中鋒
class Center : public Player
{
public:
Center(char* name) : Player(name){}
virtual void Attack()
{
printf("中鋒 %s 進攻\n", name);
}
virtual void Defense()
{
printf("中鋒 %s 防守\n", name);
}
};
// 后衛
class Guards : public Player
{
public:
Guards(char* name) : Player(name){}
virtual void Attack()
{
printf("后衛 %s 進攻\n", name);
}
virtual void Defense()
{
printf("后衛 %s 防守\n", name);
}
};
// 外籍中鋒
class ForeignCenter
{
public:
void Attack()
{
printf("外籍中鋒 %s 進攻\n", name);
}
void Defense()
{
printf("外籍中鋒 %s 防守\n", name);
}
char* name;
};
// 翻譯者
class Translator : public Player
{
public:
Translator(char* name) : Player(name)
{
wjzf.name = name;
}
virtual void Attack()
{
wjzf.Attack();
}
virtual void Defense()
{
wjzf.Defense();
}
protected:
ForeignCenter wjzf;
};
int main()
{
Player* b = new Forwards("巴蒂爾");
b->Attack();
Player* m = new Guards("麥克格雷迪");
m->Attack();
Player* ym = new Translator("姚明");
ym->Attack();
ym->Defense();
delete b;
delete m;
delete ym;
return 0;
}