姚明,你們都認識吧。在他剛去NBA的時候,什麼都聽不懂,必須在旁邊配個翻譯,不然就沒法聽懂教練在說什麼。這也正符合了設計模式中的一種模式:適配器模式。html
將一個類的接口轉換成客戶但願的另一個接口。適配器模式使得本來因爲接口不兼容而不能一塊兒工做的那些類能夠一塊兒工做。設計模式
#include <stdio.h>spa
// 球員翻譯
class Player設計
{xml
public:htm
Player(char* _name) : name(_name){}blog
virtual void Attack()=0;接口
virtual void Defense()=0;it
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;
}