适配器模式是将两个不同的接口,但是功能相似,适配的一种方法。甚至其中目标接口没有实现,实现类没有接口都是可以的。适配器模式主要强调的是接口和实现不统一,需要将两者兼容的类。
#include <iostream>
using namespace std;
//客户程序的接口,可能原本就有,也可能后来提取。这个是适配的目标接口。
class ICLient {
public:
virtual void foo01() = 0;
virtual void foo02() = 0;
virtual void foo03() = 0;
};
//客户自己原有的实现,甚至客户程序没有实现下面的功能。
class Client01 : public ICLient {
public:
void foo01() override {
cout << "客户程序foo01" << endl;
}
void foo02() override {
cout << "客户程序foo02" << endl;
}
void foo03() override {
cout << "客户程序foo03" << endl;
}
};
//客户原本的调用程序
void process(ICLient &client) {
client.foo01();
client.foo02();
client.foo03();
}
//客户程序要在我们的平台上使用,但是我们没有client类
//我们原有的Mothed类可以实现client功能。
//我们的Mothed可以没有接口,但是必须有实现。
class Mothed {
public:
void Mothed01() {
cout << "我们的方法01" << endl;
}
void Mothed02() {
cout << "我们的方法02" << endl;
}
void Mothed03() {
cout << "我们的方法03" << endl;
}
void Mothed04() {
cout << "我们的方法04" << endl;
}
};
//现在我们需要新增一个适配作用的类
class ClientMothed : public ICLient {
Mothed mothed;
public:
explicit ClientMothed() {}
void foo01() override {
mothed.Mothed01();
mothed.Mothed02();
cout << "方法01 + 方法02 相当于 foo01" << endl;
}
void foo02() override {
mothed.Mothed03();
cout << "方法03 相当于 foo02" << endl;
}
void foo03() override {
mothed.Mothed04();
cout << "方法04 相当于 foo03" << endl;
}
};
int main()
{
Client01 client01;
process(client01);
ClientMothed mothed;
process(mothed);
return 0;
}
适配模式稳定部分ICLient
,易变部分Mothed
。