【设计模式】代理模式

概念

结构型设计模式


类图


代码

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;
}
相关推荐
syt_101317 小时前
设计模式之-代理模式
设计模式·代理模式
拾忆,想起18 小时前
设计模式:软件开发的可复用武功秘籍
开发语言·python·算法·微服务·设计模式·性能优化·服务发现
老朱佩琪!20 小时前
Unity桥接模式
unity·设计模式·c#·桥接模式
winfield82120 小时前
Java 的静态代理和动态代理
java·代理模式
小明的小名叫小明20 小时前
Solidity入门(10)-智能合约设计模式1
设计模式·区块链·智能合约
小明的小名叫小明20 小时前
Solidity入门(11)-智能合约设计模式2
设计模式·区块链·智能合约
__万波__20 小时前
二十三种设计模式(十四)--命令模式
java·设计模式·命令模式
程序员zgh20 小时前
C++常用设计模式
c语言·数据结构·c++·设计模式
山风wind21 小时前
设计模式-模板方法模式详解
python·设计模式·模板方法模式