10.适配器模式

1.说明
请参见本文第一章
2.适配器模式说明
适配器模式:将一个类的接口转换成客户希望的另外一个接口。Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
通俗:需要的东西就在面前,但却不能使用,而短时间又无法改造它,于是就采用适配器来适配它。
系统的数据和行为正确,但接口不符时,我们应该考虑用适配器,目的是使控制范围之外的一个原有对象与某个接口匹配。适配器模式主要应用于希望复用一些现存类,但接口又与复用环境要求不一致的情况。
有两种模式:类适配器,对象适配器
注意1:适配器模式是在软件后期中一种补救方式,或者使用第三方软件时使用,而不会在一开始的设计中就出现这种状况
注意2:在软件开发过程中,如果出现不匹配的情况,首先应该想到的是使其匹配,如果涉及面广或其他的问题,才考虑使用适配器模式
3.UML
这里写图片描述
4.代码

//adpter基类
#ifndef __ADAPTER_H
#define __ADAPTER_H
#include <string>
class CAdapter
{
public:
    virtual int str_to_int(std::string str) = 0;
    virtual std::string int_to_str(int val) = 0;
};
#endif

//接口封装
#ifndef __SWITCHADAPTER_H
#define __SWITCHADAPTER_H

#include "Adapter.h"
#include "Switch.h"

class CSwitchAdapter:public CAdapter
{
public:
    virtual int str_to_int(std::string str)
    {
        return m_swicth.char_to_int(const_cast<char*>(str.c_str()));
    }
    virtual std::string int_to_str(int val)
    {
        std::string res;
        char buf[100];
        m_swicth.int_to_char(val, buf);
        res = buf;
        return res;
    }
private:
    CSwitch m_swicth; 

};

#endif

//源接口
#ifndef __SWITCH_H
#define __SWITCH_H

#include <string.h>
#include <stdio.h>

class CSwitch
{
public:
    void int_to_char(int val, char buf[100])
    {
        sprintf(buf, "%d", val);
    }
    int char_to_int(char* str)
    {       
        int res = 0;
        for (int i=0; i<strlen(str); i++)
            res =  res*10 + (str[i]-48);
        return res;
    }
};

#endif

//client调用

#include <iostream>
#include "SwitchAdapter.h"
#include "Adapter.h"

int main(void)
{
    CAdapter* which = new CSwitchAdapter();
    std::string str = "1234";
    std::string msg = "4567890";

    int val1 = 1234567;
    int val2 = 4567890;
    int ch1 = which->str_to_int(str);
    int ch2 = which->str_to_int(msg);
    std::cout<<"str_to_int:"<<ch1<<std::endl;
    std::cout<<"str_to_int:"<<ch2<<std::endl;

    std::string res1 = which->int_to_str(val1);
    std::string res2 = which->int_to_str(val2);
    std::cout<<"int_to_str:"<<res1.c_str()<<std::endl;
    std::cout<<"int_to_str:"<<res2.c_str()<<std::endl;
    return 0;

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值