使用一個(gè)代理類(lèi)內(nèi)部成員指針指向?qū)嶋H工作類(lèi)
跟strategy模式有點(diǎn)像首量,不同的是策略模式會(huì)有多種實(shí)現(xiàn)類(lèi)繼承虛基類(lèi)
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