【设计模式】代理模式

概念

结构型设计模式


类图


代码

cpp 复制代码
#include <iostream>

using namespace std;

class ThirdPartyTvLib {
public:
    virtual string ListVideos() = 0;
    virtual string GetVideoInfo(int id) = 0;
    virtual void DownloadVideo(int id) const = 0;
};

class ThirdPartyTvClass : public ThirdPartyTvLib {
public:
    string ListVideos() override {
        cout << "ThirdPartyTvClass list videos" << endl;
        return "xx video listed\n";
    }

    string GetVideoInfo(int id) override {
        cout << "ThirdPartyTvClass get info" << endl;
        return to_string(id) + " video info\n";
    }

    void DownloadVideo(int id) const override {
        cout << "Download " << id << " video" << endl;
    }
};

class CachedTvClass : public ThirdPartyTvLib {
public:
    CachedTvClass(ThirdPartyTvLib* thirdPartyTvLib) {
        service = thirdPartyTvLib;
    }

    string ListVideos() override {
        cout << "CachedTvClass list videos" << endl;
        if (listCache.empty() || needReset) {
            listCache = service->ListVideos();
        }

        return listCache;
    }

    string GetVideoInfo(int id) override {
        cout << "CachedTvClass get info" << endl;
        if (videoCache.empty() || needReset) {
            videoCache = service->GetVideoInfo(id);
        }

        return videoCache;
    }

    void DownloadVideo(int id) const override {
        if (!needReset) {
            service->DownloadVideo(id);
        }
    }

private:
    bool needReset{};
    ThirdPartyTvLib* service;
    string listCache, videoCache;
};

class TVManager {
public:
    TVManager(ThirdPartyTvLib* thirdPartyTvLib) {
        service = thirdPartyTvLib;
    }

    void RenderVideoPage(int id) {
        string info = service->GetVideoInfo(id);
        cout << info;
    }

    void RenderListPanel() {
        string list = service->ListVideos();
        cout << list;
    }

    void ReactOnUserInput(int id) {
        RenderVideoPage(id);
        RenderListPanel();
    }

protected:
    ThirdPartyTvLib* service;
};

int main(int argc, char *argv[]) {
    auto aTvService = new ThirdPartyTvClass();
    auto aTvProxy = new CachedTvClass(aTvService);
    auto manger = new TVManager(aTvProxy);

    manger->ReactOnUserInput(0);
    cout << "--------------------" << endl;
    manger->ReactOnUserInput(1);

    delete aTvProxy;
    delete aTvService;
    delete manger;

    return 0;
}
相关推荐
司铭鸿8 小时前
化学式解析的算法之美:从原子计数到栈的巧妙运用
linux·运维·服务器·算法·动态规划·代理模式·哈希算法
ZHE|张恒13 小时前
设计模式(十二)代理模式 — 用代理控制访问,实现延迟加载、权限控制等功能
设计模式·代理模式
SakuraOnTheWay13 小时前
《深入设计模式》学习(1)—— 深入理解OOP中的6种对象关系
设计模式
q***718513 小时前
Java进阶-SpringCloud设计模式-工厂模式的设计与详解
java·spring cloud·设计模式
白衣鸽子13 小时前
告别参数地狱:业务代码中自定义Context的最佳实践
后端·设计模式·代码规范
帅中的小灰灰1 天前
C++编程建造器设计模式
java·c++·设计模式
ZHE|张恒1 天前
设计模式(十)外观模式 — 提供统一入口,简化复杂系统的使用
设计模式·外观模式
howcode1 天前
女友去玩,竟带回一道 “虐哭程序员” 的难题
后端·设计模式·程序员
程序员-周李斌1 天前
Java 代理模式详解
java·开发语言·系统安全·代理模式·开源软件