適配器模式
1. 適配器模式:對象適配器
將一個類的接口轉換成客戶希望的另外一個接口,Adapter模式使得原本由於接口不兼容而不能一起工作的那些類可以一起工作。
簡單來說,就是需要的東西就在面前,但卻不能使用,短時間內又無法改造它,於是我們就想辦法適配它。
翻譯就是一種適配器。可以讓不會英語的人聽懂說英語人的意思。
2. 適配器模式:
主要應用於希望複用一些現存的類,但是接口又與複用環境要求不一致的情況。
何時使用?
在想使用一個已經存在的類,但如果它的接口,也就是它的方法和你的要求不相同時,就該考慮使用適配器模式。
兩個類所做的事情相同或相似,但是具有不同的接口時要使用。
通常是在軟件開發後期或維護期考慮使用。
開發起始階段,如果公司設計系統時考慮使用第三方開發組件,而這個組件的接口與我們自己的系統接口不相同時,我們也完全沒有必要爲了迎合它而改動自己的接口,此時儘管是在開發的設計階段,也可以考慮用適配器模式來解決接口不同的問題。
3. 適配器模式的例子:
#include <iostream>
#include <string>
using namespace std;
class Adaptee//需要適配的類
{
public:
virtual void myRequest()
{
cout<<"實際上的接口"<<endl;
}
};
class Target//客戶期待的接口
{
public:
virtual void request()=0;
~virtual Target(){}
};
class Adapter:public Target//在內部包裝一個Adaptee對象,把源接口轉換成目標接口
{
private:
Adaptee adaptee;
public:
void request()
{
adaptee.myRequest();
}
};
int main()
{
Target *target=new Adapter();
target->request();
delete target;
return 0;
}
//籃球翻譯適配器
class Player
{
public:
string name;
Player(string name)
{
this->name=name;
}
virtual void attack()=0;
virtual void defence()=0;
};
class Forwards:public Player
{
public:
Forwards(string name):Player(name){}
void attack()
{
cout<<name<<" 前鋒進攻"<<endl;
}
void defence()
{
cout<<name<<" 前鋒防守"<<endl;
}
};
class Center:public Player
{
public:
Center(string name):Player(name){}
void attack()
{
cout<<name<<" 中鋒進攻"<<endl;
}
void defence()
{
cout<<name<<" 中鋒防守"<<endl;
}
};
class Backwards:public Player
{
public:
Backwards(string name):Player(name){}
void attack()
{
cout<<name<<" 後衛進攻"<<endl;
}
void defence()
{
cout<<name<<" 後衛防守"<<endl;
}
};
/*****************************************************************/
class ForeignCenter
{
public:
string name;
ForeignCenter(string name)
{
this->name=name;
}
void myAttack()
{
cout<<name<<" 外籍中鋒進攻"<<endl;
}
void myDefence()
{
cout<<name<<" 外籍後衛防守"<<endl;
}
};
/*****************************************************************/
class Translator:public Player
{
private:
ForeignCenter *fc;
public:
Translator(string name):Player(name)
{
fc=new ForeignCenter(name);
}
void attack()
{
fc->myAttack();
}
void defence()
{
fc->myDefence();
}
};
/*****************************************************************/
int main()
{
Player *p1=new Center("李俊宏");
p1->attack();
p1->defence();
Translator *tl=new Translator("姚明");
tl->attack();
tl->defence();
return 0;
}