【C++設計模式】代理模式
阿新 • • 發佈:2018-12-12
#ifndef __PROXY_H__ #define __PROXY_H__ #include <string> //代理模式(Proxy):為其他物件提供一種代理以控制對這個物件的訪問。 //介面 class iSubject { public: virtual void Proc(const std::string & value) = 0; }; //真實主題 class ConcreteSubject : public iSubject { public: virtual void Proc(const std::string & value); }; //代理主題角色內部含有對真實主題的引用,提供一個與真實主題相同的介面,從而可以在任何時候替代真實主題物件。 //主題類和代理類是獨立的元件,ConcreteSubject類並不知道Proxy類的存在,在進行修改時也不會相互之間產生影響(分而治之)。 //代理 class Proxy : public iSubject { public: void DoSomething1();; void DoSomething2();; virtual void Proc(const std::string & value); private: iSubject * m_subject; }; void TestProxy(); #endif
#include "Proxy.h" void ConcreteSubject::Proc(const std::string & value) { printf("ConcreteSubject Proc %s \n",value.c_str()); } void Proxy::DoSomething1() { printf("------------------------------------------ \n"); } void Proxy::DoSomething2() { printf("------------------------------------------ \n"); } void Proxy::Proc(const std::string & value) { this->DoSomething1(); if (NULL == m_subject) { m_subject = new ConcreteSubject(); } m_subject->Proc(value); this->DoSomething2(); } void TestProxy() { iSubject * proxy = new Proxy(); proxy->Proc("12345"); }