3.6 结构型设计模式之适配器模式
一、介绍
把⼀个类的接⼝变换成客户端所期待的另⼀种接⼝
,
从⽽使原本接⼝不匹配⽽⽆法⼀起⼯作的两个类能够在⼀起⼯作。
- 类的适配器模式
- 对象的适配器模式
在上图中可以看出:
- 冲突:Target 期待调⽤ Request ⽅法,⽽ Adaptee 并没有(这就是所谓的不兼容了)。
- 解决⽅案:为使 Target 能够使⽤ Adaptee 类⾥的 SpecificRequest ⽅法 **,故提供⼀个中间环节 Adapter 类,把 Adaptee 的 API 与 Target 的 API 衔接起来 **(适配)。
二、对象适配器
将需要适配的对象进⾏包装然后提供适配后的接⼝。
** 需求:**
将 220v 墙电通过电源适配器适配出 5v 电压
1.需求接口
#ifndef _TARGET_OUTPUT_H
#define _TARGET_OUTPUT_H
class TargetOutputDc5v{
public:
virtual void outputDc5v(void) = 0;
};
#endif
2.适配者类
#ifndef _WALL_PLUG_H
#define _WALL_PLUG_H
class WallPlug{
public:
virtual void output(void) = 0;
virtual int getOutput(void) = 0;
};
#endif
//----------------------------------------------------------------------------
#ifndef _CHINA_WALL_PLUG_
#define _CHINA_WALL_PLUG_
#include "WallPlug.h"
#include <iostream>
using namespace std;
class ChinaWallPlug:public WallPlug{
public:
ChinaWallPlug();
void output(void);
int getOutput(void);
private:
int ac;
};
#endif
//----------------------------------------------------------------------------
#include "ChinaWallPlug.h"
ChinaWallPlug::ChinaWallPlug()
{
ac = 220;
}
void ChinaWallPlug::output(void)
{
cout << "output " << ac << "v" << endl;
}
int ChinaWallPlug::getOutput(void)
{
return ac;
}
3. 适配器类
#ifndef _POWER_ADAPTER_HEAD_
#define _POWER_ADAPTER_HEAD_
#include "TargetOutput.h"
#include "WallPlug.h"
class PowerAdapter:public TargetOutputDc5v{
public:
void setPowerPlug(WallPlug *wallPlug);
void outputDc5v(void);
private:
WallPlug *wallPlug;
};
#endif
//----------------------------------------------------------------------------
#include "PowerAdapter.h"
#include <iostream>
using namespace std;
void PowerAdapter::setPowerPlug(WallPlug *wallPlug)
{
this->wallPlug = wallPlug;
}
void PowerAdapter::outputDc5v(void)
{
int ac = wallPlu

最低0.47元/天 解锁文章
1650

被折叠的 条评论
为什么被折叠?



