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 }
原文:http://www.cnblogs.com/goose/p/6115239.html