Adaptor Pattern
适配器模式,把一个类的接口改成希望的接口。
考虑一个这样的类 Invoker, 缺少 method_2 方法,希望能想办法调用这个函数
class Invoker {
} ;
恰好,另一个类 Adaptee 拥有 method_2 方法
class Adaptee {
public:
void mothod_2() {}
} ;
目标是达到 Invoker 对象调用 method_2。
很容易想到复合(pimpl),内涵一个 Adaptee 指针,通过指针调用间接 method_2。为了达到 (Invoker *)ptr->(*function)() 能调用 method_2 函数。
class Invoker {
private:
std::shared_ptr<Adaptee> ptr = std::make_shared<Adaptee>();
public:
void method_1() {
ptr->method_2();
}
} ;
问题好像解决了?
考虑这样一种情况,其它类也需要调用同名函数 method_2 (STL容器就很多这种情况,例如 emplace_back, push_front, pop_back等),method_2 各异,不再是上述的 Adaptee 中的 method_2 。继续按照上面的做法,就会变成:
class Adaptee_1 {
public:
void method_2() {
std::cout << "\tAdaptee_1 的 method_2\n";
}
} ;
class Adaptee_2 {
public:
void method_2() {
std::cout << "\tAdaptee_2 的 method_2\n";
}
} ;
class Adaptee_3 {
public:
void method_2() {
std::cout << "\tAdaptee_3 的 method_2\n";
}
} ;
// ...
如果继续增加 Adaptee 类的数量,Invoker 需要包含的 Adaptee 引用越来越多,造成程序维护不便。考虑被调用的类都含有 method_2 这个函数,可以想到模板,简化编写:
template<typename adaptee>
class Invoker {
private:
std::shared_ptr<adaptee> ptr = std::make_shared<adaptee>();
public:
void method_1() {
ptr->method_2();
}
} ;
同时,假如有多个类,和 Invoker 一样需要调用名为 method_2函数 ,考虑运行时多态,统一以基类指针的方式来访问各类。具体如下:这些类命名为适配器 Adaptor_#
class Invoker {
public:
virtual void method_1() = 0;
virtual ~Invoker() = default;
} ;
template<typename adaptee>
class Adaptor_1 : public Invoker {
public:
void method_1() override {
if(ptr == nullptr)
return;
ptr->method_2();
}
private:
std::shared_ptr<adaptee> ptr = std::make_shared<adaptee>();
} ;
template<typename adaptee>
class Adaptor_2 : public Invoker {
public:
void method_1() override {
if(ptr == nullptr)
return;
ptr->method_2();
}
private:
std::shared_ptr<adaptee> ptr = std::make_shared<adaptee>();
} ;
测试代码:
#include <iostream>
#include <memory>
#include <string>
#include <vector>
// ... class 如上
int main() {
using ptrType = std::shared_ptr< Invoker >;
std::cout << "\n(Invoker*) Adaptor_1 调用";
ptrType try1 = std::make_shared< Adaptor_1<Adaptee_1> >();
try1->method_1();
std::cout << "\n(Invoker*) Adaptor_1 调用";
ptrType try2 = std::make_shared< Adaptor_1<Adaptee_2> >();
try2->method_1();
std::cout << "\n(Invoker*) Adaptor_1 调用";
ptrType try3 = std::make_shared< Adaptor_1<Adaptee_3> >();
try3->method_1();
std::cout << "\n(Invoker*) Adaptor_2 调用";
ptrType try4 = std::make_shared< Adaptor_2<Adaptee_1> >();
try4->method_1();
std::cout << "\n(Invoker*) Adaptor_2 调用";
ptrType try5 = std::make_shared< Adaptor_2<Adaptee_2> >();
try4->method_1();
std::cout << "\n(Invoker*) Adaptor_2 调用";
ptrType try6 = std::make_shared< Adaptor_2<Adaptee_3> >();
try4->method_1();
return 0;
}
运行结果:
(Invoker*) Adaptor_1 调用 Adaptee_1 的 method_2
(Invoker*) Adaptor_1 调用 Adaptee_2 的 method_2
(Invoker*) Adaptor_1 调用 Adaptee_3 的 method_2
(Invoker*) Adaptor_2 调用 Adaptee_1 的 method_2
(Invoker*) Adaptor_2 调用 Adaptee_1 的 method_2
(Invoker*) Adaptor_2 调用 Adaptee_1 的 method_2