转自:http://blog.youkuaiyun.com/fly542/article/details/6713362
首先对适配器模式做个简单的使用说明:
在以下各种情况下使用适配器模式:
1.系统需要使用现有的类,而此类的接口不符合系统的需要。
2.想要建立一个可以重复使用的类,用于与一些彼此之间没有太大关联的一些类,包括一些可能在将来引进的类一起工作。这些源类不一定有很复杂的接口。
3.(对对象适配器而言)在设计里,需要改变多个已有子类的接口,如果使用类的适配器模式,就要针对每一个子类做一个适配器,而这不太实际。
其中有两种基本的方式来实现适配器模式,a、类继承方式(下图一),b、对象方式(下图2)
(图1)
(图2)
类继承方式主要通过Adapter继承Adaptee来从新包装Adaptee的SpecificRequest到Adapter的Request函数中实现,
对象方式主要通过Adapter中包含Adaptee对象,在Adapter的Request函数中通过调用Adaptee属性对象来调用SpecificRequest函数
其中类继承方式示例代码如下
- #include <QtCore/QCoreApplication>
- #include <iostream>
- using namespace std;
- class Target
- {
- public:
- Target(){}
- virtual void request() = 0; /// >子类继承后实现相应的操作
- };
- class Adaptee
- {
- public:
- Adaptee(){}
- void SpecificRequest()
- {
- cout << " 我是特殊的接口,完成一个一般其他接口完成的不好的功能";
- }
- };
- class Adapter : public Target , private Adaptee
- {
- public:
- Adapter(){}
- virtual void request()
- {
- this->SpecificRequest(); /// >我调用特殊对象的功能,因为我继承了
- }
- };
- int main(int argc, char *argv[])
- {
- QCoreApplication a(argc, argv);
- Target * myTest = new Adapter;
- myTest->request();
- return a.exec();
- }
对象方式的代码大致如下
- #include <QtCore/QCoreApplication>
- #include <iostream>
- using namespace std;
- class Target
- {
- public:
- Target(){}
- virtual void request() = 0; /// >子类继承后实现相应的操作
- };
- class Adaptee
- {
- public:
- Adaptee(){}
- void SpecificRequest()
- {
- cout << " 我是特殊的接口,完成一个一般其他接口完成的不好的功能";
- }
- };
- class Adapter : public Target
- {
- public:
- Adapter(Adaptee* adaptee){ m_special = adaptee}
- virtual void request()
- {
- m_special->SpecificRequest(); /// >我调用特殊对象的功能,因为我继承了
- }