【设计模式】代理模式

概念

结构型设计模式


类图


代码

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;
}
相关推荐
七月丶15 小时前
别再手动凑 PR 了:这个 AI Skill 会按仓库习惯自动建分支、拆提交、提 PR
人工智能·设计模式·程序员
刀法如飞15 小时前
从程序员到架构师:6大编程范式全解析与实践对比
设计模式·系统架构·编程范式
九狼15 小时前
Flutter + Riverpod +MVI 架构下的现代状态管理
设计模式
静水流深_沧海一粟1 天前
04 | 别再写几十个参数的构造函数了——建造者模式
设计模式
StarkCoder1 天前
从UIKit到SwiftUI的迁移感悟:数据驱动的革命
设计模式
阿星AI工作室2 天前
给openclaw龙虾造了间像素办公室!实时看它写代码、摸鱼、修bug、写日报,太可爱了吧!
前端·人工智能·设计模式
_哆啦A梦2 天前
Vibe Coding 全栈专业名词清单|设计模式·基础篇(创建型+结构型核心名词)
前端·设计模式·vibecoding
阿闽ooo6 天前
中介者模式打造多人聊天室系统
c++·设计模式·中介者模式
小米4966 天前
js设计模式 --- 工厂模式
设计模式
逆境不可逃6 天前
【从零入门23种设计模式08】结构型之组合模式(含电商业务场景)
线性代数·算法·设计模式·职场和发展·矩阵·组合模式