proxy模式
2017-11-16 本文已影响0人
老练子丶2017
使用一个代理类内部成员指针指向实际工作类
跟strategy模式有点像,不同的是策略模式会有多种实现类继承虚基类
proxy.h
#ifndef _PROXY_H
#define _PROXY_H
#include <iostream>
using namespace std;
class Subject
{
public:
~Subject() {};
virtual void job()=0;
protected:
Subject() {};
};
class RealSubject : public Subject
{
public:
~RealSubject() {};
void job() {
cout << "RealSubject job" << endl;
}
};
class Proxy
{
public:
Proxy(Subject* sub) : sub_(sub) {};
~Proxy() {
if (sub_ != NULL)
delete sub_;
};
void ProxyJob() {
cout << "proxy" << endl;
sub_->job();
}
private:
Subject* sub_;
};
#endif // _PROXY_H
proxy.cpp
#include "proxy.h"
int main()
{
Subject* sub = new RealSubject;
Proxy* proxy = new Proxy(sub);
proxy->ProxyJob();
return 0;
}
编译:make proxy