模式设计-适配器模式

1.适配器模式定义

将⼀个类的接⼝转换成客户希望的另⼀个接⼝。Adapter模式使得原本由于接⼝不兼容⽽不能⼀起⼯作的那些类可以⼀起⼯作。

2.适配器模式遵循的模式设计原则

3.要点

a.原来的接⼝是稳定的,新的外来的需求是变化的,那么可以通过继承原来的接⼝,让原来的接⼝继续保持稳定,在⼦类通过组合的⽅式来扩展功能;

4.本质

转换匹配,复⽤功能;

5.代码

⽇志系统,原来是通过写磁盘的⽅式进⾏存储,后来因为查询不便,需要额外添加往数据库写⽇志的功能(写⽂件和数据库并存);

#include <string>
#include <vector>
using namespace std;

class LogSys {
public:
    LogSys() {}
    void WriteLog(const vector<string> &) {
        // ... 日志id 时间戳 服务器id 具体日志内容 roleid
    }
    vector<string>& ReadLog() {
        // ...
        vector<string> data /* = ...*/;
        return data;
    }
};

class DB;  // 面向接口编程 而不是具体类 强依赖  耦合性高  mysql mongo

class LogSysEx : public LogSys {
public:
    LogSysEx(DB *db) : _db(db) {}

    void AddLog(const vector<string> &data) {
        LogSys::WriteLog(data);
        /*
            这里调用 _db 的方法将 data 数据存储到数据库
        */
    }

    void DelLog(const int logid) {
        vector<string>& data = LogSys::ReadLog();
        // 从 vector<string> 中删除 logid的日志
        LogSys::WriteLog(data);
        // 调用 _db 的方法将 logid的日志删除
    }

    void UpdateLog(const int logid, const string &udt) {
        vector<string>& data = LogSys::ReadLog();
        // 从 vector<string> 中更新 logid的日志 udt
        LogSys::WriteLog(data);
        // 调用 _db 的方法将 logid的日志更改
    }

    string& LocateLog(const int logid) {
        vector<string>& data = LogSys::ReadLog();
        string log1 /* = from log file*/;
        string log2 /* = from db */;
        string temp = log1 + ";" + log2;
        return temp;
    }
    
private:
    DB* _db;
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值