适配器模式
在两个不兼容的接口之间搭建了一个桥梁,使得两个不同的接口可以使用。
代码实例
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// 若直接将这个函数传递进去, 则会报错
struct myPrint{
void operator()(int v1, int v2) {
cout << v1 + v2 << endl;
}
};
// 定义目标接口:要适配成什么样子的。
class Target {
public:
virtual void operator()(int v) = 0;
};
// 写适配器
class Adapter : public Target {
public:
Adapter(int param) {
this->param = param;
}
void operator()(int v) override {
print(v, param);
}
myPrint print;
int param;
};
// MyBind2nd
Adapter MyBind2nd(int v) {
return Adapter(v);
}
int main() {
vector<int> v;
for (int i = 0; i < 10; i ++) {
v.push_back(i);
}
for_each(v.begin(), v.end(), Adapter(10));
}