设计模式笔记:适配器模式

是一种结构型设计模式,使得不兼容的接口一起工作

原始使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
using namespace std;

class Target {
public:
virtual ~Target() = default;
virtual void DoSomeThing()
{
std::cout << "[Target] do some thing" << endl;
}

};

int main()
{
Target* target = nullptr;
target = new Target();

target->DoSomeThing();

return 0;
}

类适配器

「类适配器」
以多继承方式实现。

Target: 客户端期望接口类

Adaptee: 实际需要的功能类

Adapter: 将接口类与功能类衔接的适配器类

Client: 客户端代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>
using namespace std;

class Target {
public:
virtual ~Target() = default;
virtual void DoSomeThing()
{
std::cout << "[Target] do some thing" << endl;
}

};

class Adaptee {
public:
void DoSomeThing()
{
std::cout << "[Adaptee] do some thing" << endl;
}

};

class Adapter : public Target, Adaptee {
public:
void DoSomeThing()
{
Adaptee::DoSomeThing();
}
};

int main()
{
Target* target = nullptr;
target = new Adapter();

target->DoSomeThing();

return 0;
}

对象适配器

「对象适配器」
在适配器类中,包装适配者(Adaptee)接口。

Target: 客户端期望接口类

Adaptee: 实际需要的功能类

Adapter: 将接口类与功能类衔接的适配器类

Client: 客户端代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <iostream>
using namespace std;

class Target {
public:
virtual ~Target() = default;
virtual void DoSomeThing()
{
std::cout << "[Target] do some thing" << endl;
}

};

class Adaptee {
public:
void DoSomeThing()
{
std::cout << "[Adaptee] do some thing" << endl;
}

};

class Adapter : public Target {
public:
Adapter(Adaptee* adaptee) : adaptee_(adaptee) {}
void DoSomeThing()
{
if (adaptee_) {
adaptee_->DoSomeThing();
}
}

private:
Adaptee* adaptee_;
};

int main()
{
Target* target = nullptr;
Adaptee* adaptee = new Adaptee();
target = new Adapter(adaptee);

target->DoSomeThing();

delete adaptee;
return 0;
}