Proxy

Structural example

#include <iostream>
using namespace std;
 
// The 'Subject' abstract class
class Subject {
public:
	virtual void Request() = 0;
};
 
// The 'RealSubject' class
class RealSubject : public Subject {
public:
	virtual void Request() {
		cout << "Called RealSubject.Request()" << endl;
	}
};
 
// The 'Proxy' class
class Proxy : public Subject {
private:
	RealSubject *_realSubject;
public:
	Proxy() {
		_realSubject = NULL;
	}
	virtual ~Proxy() {
		if (_realSubject) delete _realSubject;
	}
	virtual void Request() {
		// Use 'lazy initialization'
		if (_realSubject == NULL) {
			_realSubject = new RealSubject;
		}
		_realSubject->Request();
	}
};
 
// Entry point into console application.
int main() {
	// Create proxy and request a service
	Proxy *proxy = new Proxy;
	proxy->Request();
 
	delete proxy;
	return 0;
}
 


Real World example

#include <iostream>
using namespace std;
 
// The 'Subject' interface
class IMath {
public:
	virtual double Add(double x, double y) = 0;
	virtual double Sub(double x, double y) = 0;
	virtual double Mul(double x, double y) = 0;
	virtual double Div(double x, double y) = 0;
};
 
// The 'RealSubject' class
class Math : public IMath {
public:
	double Add(double x, double y) { return x + y; }
	double Sub(double x, double y) { return x - y; }
	double Mul(double x, double y) { return x * y; }
	double Div(double x, double y) { return x / y; }
};
 
// The 'Proxy Object' class
class MathProxy : public IMath {
private:
	Math *_math;
public:
	MathProxy() {
		_math = new Math;
	}
	virtual ~MathProxy() {
		delete _math;
	}
	double Add(double x, double y) {
		return _math->Add(x, y);
	}
	double Sub(double x, double y) {
		return _math->Sub(x, y);
	}
	double Mul(double x, double y) {
		return _math->Mul(x, y);
	}
	double Div(double x, double y) {
		return _math->Div(x, y);
	}
};
 
// Entry point into console application.
int main() {
	// Create math proxy
	MathProxy *proxy = new MathProxy;
 
	// Do the math
	cout << "4 + 2 = " << proxy->Add(4, 2) << endl;
	cout << "4 - 2 = " << proxy->Sub(4, 2) << endl;
	cout << "4 * 2 = " << proxy->Mul(4, 2) << endl;
	cout << "4 / 2 = " << proxy->Div(4, 2) << endl;
 
	delete proxy;
	return 0;
}
 


参考サイト

デザインパターンを“喩え話”で分かり易く理解する
http://www.netlaputa.ne.jp/~hijk/study/oo/designpattern.html



デザインパターンの骸骨たち
http://www002.upp.so-net.ne.jp/ys_oota/mdp/
最終更新:2011年12月21日 01:08