軟件領域中的設計模式的重要性不言而喻。設計模式中運用了面向對象編程語言的重要特性:封裝、繼承、多態。雖然知道這些特性的定義但是並沒有做到真正的理解,這樣特性有什麼作用?用於什麼場合中等等問題,帶着疑問開始學習設計模式,主要參考《大話設計模式》和《設計模式:可複用面向對象軟件的基礎》兩本書。
適配器模式(Adapter):講一個類的接口轉換成客戶希望的另一個接口。Adapter模式使得原本由於接口不兼容而不能一起工作的那些類可以一起工作。
在軟件的開發中,也就是系統數據和行爲都正確,但是接口不符時,我們希望考慮使用適配器,目的是使得控制範圍之外的一個原有對象與某個接口匹配。適配器模式主要應用於希望複用一些現存的類,但是接口又與複雜環境要求不一致的情況,比如在需要對早期代碼複用一些功能等應用上很有實際價值。
適配器模式有兩種類型:類適配器模式和對象適配器模式;由於類適配器模式是通過多重繼承對一個藉口與另一個接口進行匹配,而C#、VB.NET、java等語言不支持多重繼承(C++支持),也對象就是一個類只有一個父類,這裏我們學習對象適配器。
#include <iostream>
using namespace std;
class Target
{
public:
virtual void Request()
{
cout << "普通的請求" << endl;
}
};
class Adaptee
{
public:
void SpecificalRequest()
{
cout << "特殊請求" << endl;
}
};
class Adapter :public Target
{
private:
Adaptee* ada;
public:
/*這樣就可以把表面上調用Request
實際是調用SpecificalRequest這就
是適配器的作用,現在接口一致*/
virtual void Request()
{
ada->SpecificalRequest();
}
Adapter()
{
ada = new Adaptee();
}
~Adapter()
{
delete ada;
}
};
//客戶端:
int main()
{
Adapter * ada = new Adapter();
ada->Request();
delete ada;
return 0;
}
#include <iostream>
#include <string>
using namespace std;
class Player
{
protected:
string name;
public:
Player(string strName) { name = strName; }
virtual void Attack() = 0;
virtual void Defense() = 0;
};
//前鋒
class Forwards : public Player
{
public:
Forwards(string strName) :Player(strName){}
public:
virtual void Attack()
{
cout << name << "前鋒進攻" << endl;
}
virtual void Defense()
{
cout << name << "前鋒防守" << endl;
}
};
//後衛
class Guards : public Player
{
public:
Guards(string strName) :Player(strName){}
public:
virtual void Attack()
{
cout << name << "後衛進攻" << endl;
}
virtual void Defense()
{
cout << name << "後衛防守" << endl;
}
};
//外籍中鋒
class Center : public Player
{
public:
Center(string strName) :Player(strName){}
public:
virtual void Attack()
{
cout << name << "中鋒進攻" << endl;
}
virtual void Defense()
{
cout << name << "中鋒防守" << endl;
}
};
//外籍中鋒
class ForeignCenter : public Player
{
public:
ForeignCenter(string strName) :Player(strName){}
public:
virtual void Attack()
{
cout << name << "外籍中鋒進攻" << endl;
}
virtual void Defense()
{
cout << name << "外籍中鋒防守" << endl;
}
};
//爲外籍中鋒翻譯
class TransLater : public Player
{
private:
ForeignCenter *player;
public:
TransLater(string strName) :Player(strName)
{
player = new ForeignCenter(strName);
}
virtual void Attack()
{
player->Attack();
}
virtual void Defense()
{
player->Defense();
}
};
//客戶端
int main()
{
Player *p = new TransLater("小李");
p->Attack();
p->Defense();
Player *p1 = new Forwards("Jams");
p1->Attack();
p1->Defense();
Player *p2 = new Guards("KoBe");
p2->Attack();
p2->Defense();
return 0;
}