以下代码来源: 设计模式精解-GoF 23种设计模式解析附C++实现源码
//****************************类模式的Adaptr********************************
//Adapter.h
#pragma once class Target { public: Target(); virtual ~Target(); virtual void Request(); protected: private: }; class Adaptee { public: Adaptee(); virtual ~Adaptee(); void SpecificRequest(); protected: private: }; class Adapter :public Target, private Adaptee { public: Adapter(); ~Adapter(); void Request(); protected: private: };
//Adapter.cpp
#include"Adapter.h" #include<iostream> Target::Target(){} Target::~Target(){} void Target::Request() { std::cout << "Target Request!!" << std::endl; } Adapter::Adapter(){} Adapter::~Adapter(){} void Adapter::Request() { this->SpecificRequest(); } Adaptee::Adaptee(){} Adaptee::~Adaptee(){} void Adaptee::SpecificRequest() { std::cout << "Specific Request!!" << std::endl; }
//main.cpp
#include"Adapter.h" #include<iostream> #include<string> int main(int args, char* argv) { Target* adt = new Adapter(); adt->Request(); getchar(); return 0; }
//****************************对象模式的Adaptr********************************
//Adapter.h
#pragma once class Target { public: Target(); virtual ~Target(); virtual void Request(); protected: private: }; class Adaptee { public: Adaptee(); virtual ~Adaptee(); void SpecificRequest(); protected: private: }; class Adapter :public Target { public: Adapter(Adaptee* adt); virtual ~Adapter(); virtual void Request(); protected: private: Adaptee* _ade; };
//Adapter.cpp
#include"Adapter.h" #include<iostream> Target::Target(){} Target::~Target(){} void Target::Request() { std::cout << "Target Request!!" << std::endl; } Adaptee::Adaptee(){} Adaptee::~Adaptee(){} void Adaptee::SpecificRequest() { std::cout << "Specific Request!!" << std::endl; } Adapter::Adapter(Adaptee* ade) { this->_ade = ade; } Adapter::~Adapter(){} void Adapter::Request() { _ade->SpecificRequest(); }
//main.cpp
#include"Adapter.h" #include<iostream> #include<string> int main(int args, char* argv) { Adaptee* ade = new Adaptee; Target* adt = new Adapter(ade); adt->Request(); getchar(); return 0; }