版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zxh2075/article/details/82870189
#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:
Proxy();
public:
void DoSomething1();;
void DoSomething2();;
virtual void Proc(const std::string & value);
private:
iSubject * m_subject;
};
void TestProxy();
#endif
#include "Proxy.h"
Proxy::Proxy()
{
m_subject = NULL;
}
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");
}