动机:现有的对象不支持新的应用环境
设计关键:在原有的接口上进行适配(并非修改原有接口)
优点:
- 有效利用现有代码,节省开发工作效率
缺点:
- 无
代码如下:
// ConsoleApplication1.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include<iostream>
using namespace std;
class ITarget
{
public:
virtual void process() = 0;
};
class IAdapter
{
public:
virtual void bar() = 0;
virtual void foo() = 0;
};
class OldClass :public IAdapter
{
public:
virtual void bar() override
{
cout << "OldClass bar " << endl;
}
virtual void foo() override
{
cout << "OldClass foo " << endl;
}
};
class AdapterClass:public ITarget
{
private:
IAdapter* m_target;
public:
AdapterClass(IAdapter* p)
{
m_target = p;
}
virtual void process()
{
m_target->bar();
m_target->foo();
}
};
int main()
{
OldClass nAdapt;
ITarget* nTarget =new AdapterClass(&nAdapt);
nTarget->process();
delete nTarget;
return 1;
}