cplusplus 适配器模式
#include <iostream> using namespace std; class Target{ //target接口 public: virtual void eat() = 0; virtual void sleep() = 0; }; class Adaptee{ public: void eat(int n){ cout<<"eat cost: "<<n<<" seconds"<<endl; } void sleep(int n){ cout<<"sleep for "<<n<<" seconds"<<endl; } }; class Adapter: public Target, public Adaptee{ public: void eat(){ cout<<"adapter "; Adaptee::eat(10); } void sleep(){ cout<<"adapter "; Adaptee::sleep(10); } }; int main(){ Target* pobj = (Target* ) new Adapter(); pobj->eat(); pobj->sleep(); delete pobj; return 0;// }
成员变量形式的适配器模式
#include <iostream> using namespace std; class Target{ //target接口 public: virtual void eat() = 0; virtual void sleep() = 0; }; class Adaptee{ public: void eat(int n){ cout<<"eat cost: "<<n<<" seconds"<<endl; } void sleep(int n){ cout<<"sleep for "<<n<<" seconds"<<endl; } }; class Adapter: public Target{ public: Adapter(shared_ptr<Adaptee>& pobj){ this->pobj = pobj; } ~Adapter(){ } void eat(){ cout<<"adapter "; this->pobj->eat(10); } void sleep(){ cout<<"adapter "; this->pobj->sleep(10); } private: shared_ptr<Adaptee> pobj; }; int main(){ //shared_ptr<Adaptee> sp(new Adaptee()); shared_ptr<Adaptee> sp; sp = make_shared<Adaptee>(); Target* pobj = (Target* ) new Adapter(sp); pobj->eat(); pobj->sleep(); delete pobj; return 0; }

浙公网安备 33010602011771号