上次说到adapter模式有两种,一种是对象的adapter模式,一种是对象的adapter模式,我们知道adapter模式主要是为了使得不可兼容的接口可以在一起使用,关于类的adapter模
式主要是使用了对象继承,使得adapter共有集成了Target,私有继承了adaptee,在Target的SpecificRequest函数中调用了adaptee的Request函数。而对象的adapter模式则是
使用了对象组合的方式实现了adapter模式
代码实现:
#includeusing namespace std; class target { public: target() {;} ~target() {;} void specificRequest() {;} }; class adaptee { public: adaptee() {;} ~adaptee() {;} void Request() { cout<<"adaptee::Request\n"; } }; class adapter: public target { public: adaptee* m_adaptee; adapter(adaptee* e) { m_adaptee=e; } ~adapter() {;} void specificRequest() { m_adaptee->Request(); } }; int main() { adaptee*tmp=new adaptee(); target* real_ptr=new adapter(tmp); tmp->specificRequest(); }
以上便是对象的adapter模式实现,我们知道comprision over inherience对象组合优于对象继承