【设计模式】代理模式

概念

结构型设计模式


类图


代码

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;
}
相关推荐
糟糕好吃10 小时前
AI 全流程解析(LLM / Token / Context / RAG / Prompt / Tool / Skill / Agent)
前端·后端·设计模式
花月C11 小时前
线性动态规划(Linear DP)
算法·动态规划·代理模式
kvo7f2JTy13 小时前
JAVA 设计模式
java·开发语言·设计模式
程序员小寒15 小时前
JavaScript设计模式(九):工厂模式实现与应用
开发语言·前端·javascript·设计模式
LanceJiang16 小时前
设计模式在前端的简易实现与作用
前端·设计模式
散峰而望17 小时前
【基础算法】动态规划从入门到进阶:记忆化搜索、线性 DP、LIS/LCS 一网打尽
c++·后端·算法·github·深度优先·动态规划·代理模式
Lyyaoo.18 小时前
【设计模式】工厂模式
java·开发语言·设计模式
楼田莉子18 小时前
设计模式:设计模式的相关概念与原则
c++·学习·设计模式
淡忘旧梦19 小时前
ChatGPT回答白屏
人工智能·chatgpt·代理模式
会编程的土豆1 天前
【数据结构与算法】动态规划
数据结构·c++·算法·leetcode·代理模式