适配器模式

作用:使原本因接口不兼容而不能一起工作的类能够协同工作。

适用场景:当想复用某个类,而类的接口与环境不符,此时可以考虑使用适配器模式。用适配器封装被适配的对象,让接口由适配器提供,具体功能由被适配对象提供。

关键代码:

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();

}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值