//类适配器 #include<memory> #include<iostream> using namespace std; class Target { public: virtual void request(){ cout << "Target::Request"<<endl; } }; class Adaptee{ public: void SpecificRequest(){ cout << "adaptee::SpecificRequest()"<<endl; } }; class Adapter : public Target , Adaptee{ public: void request(){ Adaptee::SpecificRequest (); } }; int main(int argc, char *argv[]) { auto_ptr<Target> tarobj ( new Adapter() );//适配器就是引入中间类进行后台链接 //Target *tarobj = new Adapter(); tarobj->request (); return 0; }
//对象适配器(比类适配器常用) #include<iostream> #include<memory> using namespace std; class Target { public: Target() {} virtual ~Target(){ cout <<"delete target"<<endl; } virtual void Request(){ cout << "Target request" << endl; } }; class Adaptee { public: Adaptee() {} void SpecialRequest(){ cout << "Adaptee::request" <<endl; } }; class Adapter : public Target { public: Adapter() : m_Adaptee(new Adaptee()){} ~Adapter(){ if( m_Adaptee != NULL){ delete m_Adaptee; cout << "delete Adaptee"<<endl; m_Adaptee = NULL; } } void Request (){ m_Adaptee->SpecialRequest (); } private: Adaptee *m_Adaptee; }; int main(int argc, char *argv[]) { auto_ptr<Target> tarobj (new Adapter()); tarobj->Request (); return 0; }
原文:http://blog.csdn.net/emb_hqj/article/details/43878957