适用情境:在源接口和目标接口都不适宜修改的情况下,把源接口转换成目标接口.
// target.h
#ifndef TARGET_H
#define TARGET_H
class Target
{
public:
Target();
virtual void Request();
};
#endif // TARGET_H
// target.cpp
#include "target.h"
#include <iostream>
Target::Target(){}
void Target::Request()
{
std::cout << "target request" << std::endl;
}
// adaptee.h
#ifndef ADAPTEE_H
#define ADAPTEE_H
class Adaptee
{
public:
Adaptee();
virtual void MyRequest();
};
#endif // ADAPTEE_H
// adaptee.cpp
#include "adaptee.h"
#include <iostream>
Adaptee::Adaptee(){}
void Adaptee::MyRequest()
{
std::cout << "adaptee my request" << std::endl;
}
// adapter.h
#ifndef ADAPTER_H
#define ADAPTER_H
#include "target.h"
#include "adaptee.h"
class Adapter : public Target
{
public:
Adapter();
~Adapter();
virtual void Request();
private:
Adaptee* m_adaptee;
};
#endif // ADAPTER_H
// adapter.cpp
#include "adapter.h"
#include <iostream>
Adapter::Adapter()
{
m_adaptee = new Adaptee();
}
Adapter::~Adapter()
{
delete m_adaptee;
}
void Adapter::Request()
{
m_adaptee->MyRequest();
Target::Request();
}
客户端:
// main.cpp
#include <iostream>
#include "target.h"
#include "adapter.h"
using namespace std;
int main(int argc, char *argv[])
{
Target *target = new Adapter();
target->Request();
delete target;
return 0;
}