类适配器
#include <iostream>
using namespace std;
// Target
class Target {
public:
virtual void Request() {
cout << "Target::Request" << endl;
}
};
// Adaptee
class Adaptee {
public:
void SpecificRequest() {
cout << "Adaptee::SpecificRequest" << endl;
}
};
// Adapter
class Adapter : public Target,Adaptee {
public:
void Request() {
Adaptee::SpecificRequest();
}
};
// Client
int main() {
Target * pTarget = new Adapter();
pTarget->Request();
if (pTarget) delete pTarget;
return 0;
}
对象适配器
#include <iostream>
using namespace std;
// Target
class Target {
public:
Target(){}
virtual ~Target(){}
virtual void Request() {
cout << "Target::Request" << endl;
}
};
// Adaptee
class Adaptee {
public:
void SpecificRequest() {
cout << "Adaptee::SpecificRequest" << endl;
}
};
// Adapter
class Adapter : public Target,Adaptee {
public:
Adapter() : m_Adaptee(new Adaptee) {}
~Adapter() {
if (m_Adaptee != NULL) {
delete m_Adaptee;
}
}
void Request() {
m_Adaptee->SpecificRequest();
}
private:
Adaptee *m_Adaptee;
};
// Client
int main() {
Target * pTarget = new Adapter();
pTarget->Request();
if (pTarget) delete pTarget;
return 0;
}