proxy模式

使用一个代理类内部成员指针指向实际工作类

跟strategy模式有点像,不同的是策略模式会有多种实现类继承虚基类

proxy.h

#ifndef _PROXY_H

#define _PROXY_H

#include

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

你可能感兴趣的:(proxy模式)