C++中的适配器模式
一、为什么需要适配器模式
当你想使用一格现存的类,但是它的方法和你的要求不相同时,此时就需要使用适配器模式。
二、适配器的作用是什么
适配器就是将一个类的接口转换成客户希望的另外一个接口,适配器模式使得原本由于接口不兼容而不能一起工作的类可以一起工作。
三、适配器模式的分类
适配器模式可以分为两类,一种是类模式适配器,另一种是对象模式适配器。
类模式适配器
// 目标接口类,客户需要的接口 class Target { public: Target(); virtual ~Target(); virtual void Request(); }; // 需要适配的类 class Adaptee { public: Adaptee(); ~Adaptee(); void SpecificRequest(); }; // 适配器类,通过public继承获得接口继承的效果,通过private继承获得实现继承的效果 class Adapter : public Target, private Adaptee { public: Adapter(); ~Adapter(); virtual void Request(); }; Target::Target() { } Target::~Target() { } void Target::Request() { std::cout << "Target::Request()" << std::endl; } Adaptee::Adaptee() { } Adaptee::~Adaptee() { } void Adaptee::SpecificRequest() { std::cout << "Adaptee::SpecificRequest()" << std::endl; } Adapter::Adapter() { } Adapter::~Adapter() { } void Adapter::Request() { std::cout << "Adapetr::Request()" << std::endl; this->SpecificRequest(); std::cout << "------------------" << std::endl; } int main() { Target* pTarget = new Adapter(); pTarget->Request(); }
类模式Adapter的关键在于适配器类需要public继承目标接口类(客户需要的接口),并且private继承需要适配的类。
对象模式适配器
// 目标接口类,客户需要的接口 class Target { public: Target(); virtual ~Target(); virtual void Request(); }; // 需要适配的类 class Adaptee { public: Adaptee(); ~Adaptee(); void SpecificRequest(); }; // 适配器类,通过public继承获得接口继承的效果,通过private继承获得实现继承的效果 class Adapter : public Target { public: Adapter(Adaptee* adaptee); Adapter(); ~Adapter(); virtual void Request(); private: Adaptee* mAdaptee; }; Target::Target() { } Target::~Target() { } void Target::Request() { std::cout << "Target::Request()" << std::endl; } Adaptee::Adaptee() { } Adaptee::~Adaptee() { } void Adaptee::SpecificRequest() { std::cout << "Adaptee::SpecificRequest()" << std::endl; } Adapter::Adapter(): mAdaptee(new Adaptee) { } Adapter::Adapter(Adaptee* adapteee) { mAdaptee = adaptee; } Adapter::~Adapter() { } void Adapter::Request() { std::cout << "Adapetr::Request()" << std::endl; this->mAdaptee->SpecificRequest(); std::cout << "------------------" << std::endl; } int main() { Adaptee* ade = new Adaptee(); Target* pTarget = new Adapter(ade); pTarget->Request(); }
对象模式适配器和类模式适配器的关键区别在于适配器类只public继承了目标接口类(客户需要的接口),而在类中维护了一个需要适配的类的实例。
四、参考资料
本文参考自文章C++设计模式-Adapter适配器模式