设计模式读书笔记:Proxy(代理)
2015-07-10 17:23:50
意图:
为其他对象提供一种代理以控制对这个对象的访问。
结构图:来自 《23种设计模式 - 郗晓勇》
实现:https://github.com/panshiqu/patterns/tree/master/Proxy
Subject
namespace NS_PROXY {
class Subject {
public:
Subject() {}
virtual ~Subject() {}
virtual void Request(void) = 0;
};
} /* namespace NS_PROXY */
RealSubject
#include <iostream>
namespace NS_PROXY {
class RealSubject {
public:
RealSubject() {}
virtual ~RealSubject() {}
virtual void Request(void)
{
std::cout << "Request RealSubject." << std::endl;
}
};
} /* namespace NS_PROXY */
Proxy
#include "RealSubject.h"
namespace NS_PROXY {
class Proxy {
public:
Proxy() : _realSubject(0) {}
virtual ~Proxy()
{
if (_realSubject != 0)
delete _realSubject;
}
virtual void Request(void)
{
if (_realSubject == 0)
_realSubject = new RealSubject();
_realSubject->Request();
}
private:
RealSubject *_realSubject;
};
} /* namespace NS_PROXY */
main
#include "Proxy/Proxy.h"
using namespace NS_PROXY;
int main(void)
{
Proxy p;
p.Request();
}
附加: