Adapter Pattern
1.Adapter模式用来实现将一个类(第三方库)的接口转换为客户(购买使用者)希望的接口。
Adapter模式有两种类别:类模式、对象模式。类模式采用继承的方式复用Adaptee的接口,对象模式通过组合的方式实现Adaptee的复用。
2.Adapter模式结构图:
3.类模式实现
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #ifndef _ADAPTER_H_ 2 #define _ADAPTER_H_ 3 4 class Target 5 { 6 public: 7 Target(); 8 virtual ~Target(); 9 virtual void Request(); 10 protected: 11 private: 12 }; 13 14 class Adaptee 15 { 16 public: 17 Adaptee(); 18 ~Adaptee(); 19 void SpecificRequest(); 20 protected: 21 private: 22 }; 23 24 class Adapter:public Target,private Adaptee 25 { 26 public: 27 Adapter(); 28 ~Adapter(); 29 void Request(); 30 protected: 31 private: 32 }; 33 34 #endif
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include "Adapter.h" 2 #include <iostream> 3 4 Target::Target() 5 { 6 7 } 8 Target::~Target() 9 { 10 11 } 12 void Target::Request() 13 { 14 std::cout<<"Target::Request"<<std::endl; 15 } 16 Adaptee::Adaptee() 17 { 18 19 } 20 Adaptee::~Adaptee() 21 { 22 23 } 24 void Adaptee::SpecificRequest() 25 { 26 std::cout<<"Adaptee::SpecificRequest" <<std::endl; 27 } 28 Adapter::Adapter() 29 { 30 31 } 32 Adapter::~Adapter() 33 { 34 35 } 36 void Adapter::Request() 37 { 38 this->SpecificRequest(); 39 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include "Adapter.h" 2 #include <iostream> 3 using namespace std; 4 5 int main(int argc,char* argv[]) 6 { //Adapter* adt = new Adapter(); 7 Target* adt = new Adapter(); 8 adt->Request(); 9 return 0; 10 }
4.对象模式实现
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #ifndef _ADAPTER_H_ 2 #define _ADAPTER_H_ 3 4 class Target 5 { 6 public: 7 Target(); 8 virtual ~Target(); 9 virtual void Request(); 10 protected: 11 private: 12 }; 13 14 class Adaptee 15 { 16 public: 17 Adaptee(); 18 ~Adaptee(); 19 void SpecificRequest(); 20 protected: 21 private: 22 }; 23 24 class Adapter:public Target 25 { 26 public: 27 Adapter(Adaptee* ade); 28 ~Adapter(); 29 void Request(); 30 protected: 31 private: 32 Adaptee* _ade; 33 }; 34 35 #endif
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include "Adapter.h" 2 #include <iostream> 3 4 Target::Target() 5 { 6 7 } 8 Target::~Target() 9 { 10 11 } 12 void Target::Request() 13 { 14 std::cout<<"Target::Request"<<std::endl; 15 } 16 Adaptee::Adaptee() 17 { 18 19 } 20 Adaptee::~Adaptee() 21 { 22 23 } 24 void Adaptee::SpecificRequest() 25 { 26 std::cout<<"Adaptee::SpecificRequest" <<std::endl; 27 } 28 Adapter::Adapter(Adaptee* ade) 29 { 30 this->_ade = ade; 31 } 32 Adapter::~Adapter() 33 { 34 35 } 36 void Adapter::Request() 37 { 38 _ade->SpecificRequest(); 39 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include "Adapter.h" 2 #include <iostream> 3 using namespace std; 4 5 int main(int argc,char* argv[]) 6 { //Adapter* adt = new Adapter(); 7 Adaptee* ade = new Adaptee; 8 Target* adt = new Adapter(ade); 9 adt->Request(); 10 return 0; 11 }