代理模式(Proxy)

/* AOP:叫面向方面(切面)编程 在我们的日常开发中,我们经常会遇到这样的一类与业务逻辑无关 的开发,正交化 打log,将log进入织入我们的业务场景 */ #include <memory> #include <string> #include <iostream> using namespace std; class IHello { public: IHello(){} virtual ~IHello() { } virtual void Output(const string& str){} }; class Hello :public IHello { public: void Output(const string& str) override { cout << str << endl; } }; class HelloProxy :public IHello { public: HelloProxy(IHello *p) :m_ptr(p) { } ~HelloProxy(){ delete m_ptr; m_ptr = nullptr; } void Output(const string& str) final { cout << "在真正的对象执行之前,进行拦截" << endl; m_ptr->Output(str); cout << "在真正的对象执行之后,进行拦截" << endl; } private: IHello* m_ptr; }; int main(void) { std::shared_ptr<IHello> hello = std::make_shared<HelloProxy>(new Hello()); hello->Output("AOP 测试"); system("pause"); return 0; }

#include <iostream> #include <string> #include <fstream> #include <sstream> #include <map> #include <vector> using namespace std; //切分成log: /// 故障名,故障时间,故障描述 ///map<int,vector<string>>:int 故障的序号,然后我们将这些( 故障名|故障时间|故障描述) map<int, vector<string>> Cache; //class BugManager { //public: // virtual void getBug() = 0; //}; class RealBugModel { public: void getBugs() { //从文件读取,并且将故障信息封装进入Cache中 ifstream in("e:\\tmp\\故障列表.txt"); if (!in) { cerr << "文件打开错误" << endl; system("pause"); } string line; int i = 0; while (getline(in, line)) { Cache[i] = getCache(line); i++; } in.close(); } private: vector<string> getCache(string words) { vector<string> results; istringstream ss(words); while (!ss.eof()) { string word; getline(ss, word, '|'); results.push_back(word); } return results; } }; class ProxyBugModel { public: ProxyBugModel() :m_reload(false) { } void getBugs() { if (m_reload) { cout << "这是从缓存里面获取的" << endl; showBugs(); } else { cout << "这是真实的数据" << endl; (new RealBugModel())->getBugs(); m_reload = true; showBugs(); } } private: void showBugs() { for (int i = 0;i < Cache.size();i++) { cout << "第" << i << "行是"; for (vector<string>::iterator iter = Cache[i].begin();iter != Cache[i].end();iter++) { cout << (*iter) << " "; } cout << endl; } } private: bool m_reload;//如果reload为真,表示,这个是从缓存里面拿的,否则,我们请求真正的realbug对象 }; int main(void) { ProxyBugModel* p = new ProxyBugModel(); for (int i = 0;i < 5;i++) { cout << "第" << i << "次请求" << endl; p->getBugs(); } system("pause"); return 0; }
远程代理.cpp
智能指针.cpp
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!