作用:使原本因接口不兼容而不能一起工作的类能够协同工作。
适用场景:当想复用某个类,而类的接口与环境不符,此时可以考虑使用适配器模式。用适配器封装被适配的对象,让接口由适配器提供,具体功能由被适配对象提供。
关键代码:
1.target:目标接口
2.adptee:被适配对象
3.adpter:适配器
实现:有类适配器和对象适配器,如下图:
图1:类模式适配器
图2:对象模式适配器
代码:
#include <cstdio>
#include <stack>
#include <set>
#include <iostream>
#include <string>
#include <vector>
#include <queue>
#include <list>
#include <functional>
#include <cstring>
#include <algorithm>
#include <cctype>
#include <string>
#include <map>
#include <iomanip>
#include <cmath>
#include <time.h>
#define LL long long
using namespace std;
// 目标接口类,客户希望的接口
class target
{
public:
virtual void readDisk()
{
puts("read from disk");
}
};
// 被适配的类
class adptee
{
public:
void readRAM()
{
puts("read from ram");
}
};
// 类模式适配器
class adpter_1:public target,public adptee
{
public:
void readDisk()
{
readRAM();
}
};
// 对象模式适配器
class adpter_2:public target
{
private:
adptee *adp;
public:
~adpter_2()
{
delete adp;
}
adpter_2(adptee *p)
{
adp=p;
}
void readDisk()
{
adp->readRAM();
}
};
int main()
{
target *p = new adpter_1();
p->readDisk();
delete p;
target *t = new adpter_2(new adptee);
t->readDisk();
}