适配器模式、代理模式、策略模式、观察者模式

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
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值