最近在看《大话设计模式》这本书,看到了代理模式这一章,正好有时间,简单的写一下自己的理解。
代理模式就是其实就是对 真实的实体做了一层封装,客户端调用的时候 直接访问代理类,代理类再根据实际情况去操作真实的实体。在操作实体之前,代理类可以做一些判定或者其他的操作,这就是代理类存在的意义。一般代理类中都会保存一个 实体类的对象的引用或者指针。
代理类和实体类具有相同的接口,一般情况下他们继承自一个接口类。
1.UML图:
2.代码:
Proxy.h
#ifndef PROXY_H_
#define PROXY_H_
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <string.h>
using std::string;
class Subject
{
public:
Subject() {};
virtual ~Subject() {};
virtual void Request() = 0;
};
//实体类
class RealSubject :public Subject
{
public:
RealSubject();
RealSubject(string &strName);
~RealSubject();
void Request();
private:
string m_strName;
};
//代理类
class Proxy :public Subject
{
public:
Proxy();
~Proxy();
void SetSubject(RealSubject *pRealSubject); //设置内部实体对象
void Request();
private:
RealSubject *m_pRealSubject; //代理类内部的实体类引用
};
#endif
proxy.cpp:
#include "Proxy.h"
RealSubject::RealSubject()
{
}
RealSubject::RealSubject(string &strName)
{
m_strName = strName;
}
RealSubject::~RealSubject()
{
}
void RealSubject::Request()
{
printf("RealSuject Name : %s\n", m_strName.c_str());
}
Proxy::Proxy()
{
m_pRealSubject = NULL;
}
Proxy::~Proxy()
{
if (m_pRealSubject)
{
delete m_pRealSubject;
m_pRealSubject = NULL;
}
}
void Proxy::SetSubject(RealSubject *pRealSubject)
{
if (m_pRealSubject)
{
delete m_pRealSubject;
m_pRealSubject = NULL;
}
m_pRealSubject = pRealSubject;
}
void Proxy::Request()
{
if (NULL == m_pRealSubject)
{
string strName = "RealSubject";
m_pRealSubject = new RealSubject(strName);
}
//做一些代理需要做的事情
printf("Proxy do something\n");
m_pRealSubject->Request();
}
Test.cpp:
#include "Proxy.h"
int main()
{
//1
Proxy *pProxy = new Proxy();
pProxy->Request();
delete pProxy;
pProxy = NULL;
//2
string strName = "MyRealSubject";
RealSubject *pRealSubject = new RealSubject(strName);
pProxy = new Proxy();
pProxy->SetSubject(pRealSubject);
pProxy->Request();
delete pProxy;
pProxy = NULL;
return 0;
}