现在的位置: 首页 > 综合 > 正文

设计模式—Adapter模式

2013年04月18日 ⁄ 综合 ⁄ 共 1716字 ⁄ 字号 评论关闭

转自:http://blog.csdn.net/fly542/article/details/6713362

首先对适配器模式做个简单的使用说明:

在以下各种情况下使用适配器模式:
1.系统需要使用现有的类,而此类的接口不符合系统的需要。
2.想要建立一个可以重复使用的类,用于与一些彼此之间没有太大关联的一些类,包括一些可能在将来引进的类一起工作。这些源类不一定有很复杂的接口。
3.(对对象适配器而言)在设计里,需要改变多个已有子类的接口,如果使用类的适配器模式,就要针对每一个子类做一个适配器,而这不太实际。

其中有两种基本的方式来实现适配器模式,a、类继承方式(下图一),b、对象方式(下图2)

(图1)

 

(图2)

类继承方式主要通过Adapter继承Adaptee来从新包装Adaptee的SpecificRequest到Adapter的Request函数中实现,

对象方式主要通过Adapter中包含Adaptee对象,在Adapter的Request函数中通过调用Adaptee属性对象来调用SpecificRequest函数

 

其中类继承方式示例代码如下

  1. #include <QtCore/QCoreApplication>  
  2. #include <iostream>  
  3.   
  4. using namespace std;  
  5.   
  6. class Target  
  7. {  
  8. public:  
  9.     Target(){}  
  10.     virtual void request() = 0; /// >子类继承后实现相应的操作  
  11. };  
  12.   
  13.   
  14. class Adaptee  
  15. {  
  16. public:  
  17.     Adaptee(){}  
  18.     void SpecificRequest()  
  19.     {  
  20.         cout << " 我是特殊的接口,完成一个一般其他接口完成的不好的功能";  
  21.     }  
  22. };  
  23.   
  24. class Adapter : public Target , private Adaptee  
  25. {  
  26. public:  
  27.     Adapter(){}  
  28.     virtual void request()  
  29.     {  
  30.         this->SpecificRequest(); /// >我调用特殊对象的功能,因为我继承了  
  31.     }  
  32. };  
  33.   
  34. int main(int argc, char *argv[])  
  35. {  
  36.     QCoreApplication a(argc, argv);  
  37.   
  38.     Target * myTest = new Adapter;  
  39.     myTest->request();  
  40.     return a.exec();  
  41. }  


对象方式的代码大致如下

  1. #include <QtCore/QCoreApplication>  
  2. #include <iostream>  
  3.   
  4. using namespace std;  
  5.   
  6. class Target  
  7. {  
  8. public:  
  9.     Target(){}  
  10.     virtual void request() = 0; /// >子类继承后实现相应的操作  
  11. };  
  12.   
  13.   
  14. class Adaptee  
  15. {  
  16. public:  
  17.     Adaptee(){}  
  18.     void SpecificRequest()  
  19.     {  
  20.         cout << " 我是特殊的接口,完成一个一般其他接口完成的不好的功能";  
  21.     }  
  22. };  
  23.   
  24. class Adapter : public Target   
  25. {  
  26. public:  
  27.     Adapter(Adaptee* adaptee){ m_special = adaptee}  
  28.     virtual void request()  
  29.     {  
  30.         m_special->SpecificRequest(); /// >我调用特殊对象的功能,因为我继承了  
  31.     }  

抱歉!评论已关闭.