Adapter適配器模式
作用:將一個類的接口轉換成客戶希望的另外一個接口。Adapter模式使得原本由於接口不兼容而不能一起工作的那些類可以一起工作。
分為類適配器模式和對象適配器模式。
系統的數據和行為都正確,但接口不符時,我們應該考慮使用適配器,目的是使控制范圍之外的一個原有對象與某個接口匹配。適配器模式主要應用於希望復用一些現存的類,但是接口又與復用環境要求不一致的情況。
想使用一個已經存在的類,但如果它的接口,也就是它的方法和你的要求不相同時,就應該考慮用適配器模式。
比如購買的第三方開發組件,該組件接口與我們自己系統的接口不相同,或者由於某種原因無法直接調用該組件,可以考慮適配器。
UML圖如下:
圖1:類模式適配器
圖2:對象模式適配器
代碼如下:
Adapter.h
1 #ifndef _ADAPTER_H_ 2 #define _ADAPTER_H_ 3 4 //目標接口類,客戶需要的接口 5 class Target 6 { 7 public: 8 Target(); 9 virtual ~Target(); 10 virtual void Request();//定義標准接口 11 }; 12 13 //需要適配的類 14 class Adaptee 15 { 16 public: 17 Adaptee(); 18 ~Adaptee(); 19 void SpecificRequest(); 20 }; 21 22 //類模式,適配器類,通過public繼承獲得接口繼承的效果,通過private繼承獲得實現繼承的效果 23 class Adapter:public Target,private Adaptee 24 { 25 public: 26 Adapter(); 27 ~Adapter(); 28 virtual void Request();//實現Target定義的Request接口 29 }; 30 31 //對象模式,適配器類,繼承Target類,采用組合的方式實現Adaptee的復用 32 class Adapter1:public Target 33 { 34 public: 35 Adapter1(Adaptee* adaptee); 36 Adapter1(); 37 ~Adapter1(); 38 virtual void Request();//實現Target定義的Request接口 39 private: 40 Adaptee* _adaptee; 41 }; 42 #endif
Adapter.cpp
1 #include "Adapter.h" 2 #include <iostream> 3 4 using namespace std; 5 6 Target::Target() 7 {} 8 9 Target::~Target() 10 {} 11 12 void Target::Request() 13 { 14 cout << "Target::Request()" << endl; 15 } 16 17 Adaptee::Adaptee() 18 { 19 } 20 21 Adaptee::~Adaptee() 22 { 23 } 24 25 void Adaptee::SpecificRequest() 26 { 27 cout << "Adaptee::SpecificRequest()" << endl; 28 } 29 30 //類模式的Adapter 31 Adapter::Adapter() 32 { 33 } 34 35 Adapter::~Adapter() 36 { 37 } 38 39 void Adapter::Request() 40 { 41 cout << "Adapter::Request()" << endl; 42 this->SpecificRequest(); 43 cout << "----------------------------" <<endl; 44 } 45 46 //對象模式的Adapter 47 Adapter1::Adapter1():_adaptee(new Adaptee) 48 { 49 } 50 51 Adapter1::Adapter1(Adaptee* _adaptee) 52 { 53 this->_adaptee = _adaptee; 54 } 55 56 Adapter1::~Adapter1() 57 { 58 } 59 60 void Adapter1::Request() 61 { 62 cout << "Adapter1::Request()" << endl; 63 this->_adaptee->SpecificRequest(); 64 cout << "----------------------------" <<endl; 65 }
main.cpp
1 #include "Adapter.h" 2 3 int main() 4 { 5 //類模式Adapter 6 Target* pTarget = new Adapter(); 7 pTarget->Request(); 8 9 //對象模式Adapter1 10 Adaptee* ade = new Adaptee(); 11 Target* pTarget1= new Adapter1(ade); 12 pTarget1->Request(); 13 14 //對象模式Adapter2 15 Target* pTarget2 = new Adapter1(); 16 pTarget2->Request(); 17 18 return 0; 19 }
在Adapter模式的兩種模式中,有一個很重要的概念就是接口繼承和實現繼承的區別和聯系。接口繼承和實現繼承是面向對象領域的兩個重要的概念,接口繼承指的是通過繼承,子類獲得了父類的接口,而實現繼承指的是通過繼承子類獲得了父類的實現(並不統共接口)。在C++中的public繼承既是接口繼承又是實現繼承,因為子類在繼承了父類后既可以對外提供父類中的接口操作,又可以獲得父類的接口實現。當然我們可以通過一定的方式和技術模擬單獨的接口繼承和實現繼承,例如我們可以通過private繼承獲得實現繼承的效果(private繼承后,父類中的接口都變為private,當然只能是實現繼承了。),通過純抽象基類模擬接口繼承的效果,但是在C++中pure virtual function也可以提供默認實現,因此這是不純正的接口繼承,但是在Java中我們可以interface來獲得真正的接口繼承了。