// ProxyTest.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> using namespace std; //为其他对象提供一种代理以控制对这个对象的访问 class ISubject { public: virtual int Add(int a, int b) = 0; virtual int Sub(int a, int b) = 0; virtual int Mul(int a, int b) = 0; virtual int Div(int a, int b) = 0; virtual ~ISubject(void) { } }; class CRealSubject : public ISubject { public: virtual int Add(int a, int b) { return a + b; } virtual int Sub(int a, int b) { return a - b; } virtual int Mul(int a, int b) { return a * b; } virtual int Div(int a, int b) { return b != 0 ? a / b : 0; } }; class CProxySubject : public ISubject { public: //允许创建空代理 CProxySubject(CRealSubject* pRealSubject = NULL) : m_pRealSubject(pRealSubject) { } virtual ~CProxySubject(void) { Unitialize(); } void Unitialize(void) { if (m_pRealSubject != NULL) { delete m_pRealSubject; m_pRealSubject = NULL; } } void Initialize(void) { if (m_pRealSubject == NULL) { m_pRealSubject = new CRealSubject; } } virtual int Add(int a, int b) { Initialize(); return m_pRealSubject->Add(a, b); } virtual int Sub(int a, int b) { Initialize(); return m_pRealSubject->Sub(a, b); } virtual int Mul(int a, int b) { Initialize(); return m_pRealSubject->Mul(a, b); } virtual int Div(int a, int b) { Initialize(); return m_pRealSubject->Div(a, b); } private: CRealSubject* m_pRealSubject; }; int _tmain(int argc, _TCHAR* argv[]) { CProxySubject* pProxySubject = new CProxySubject(); cout << pProxySubject->Add(10, 11) << endl; cout << pProxySubject->Sub(21, 10) << endl; cout << pProxySubject->Mul(11, 11) << endl; cout << pProxySubject->Div(300, 30) << endl; delete pProxySubject; return 0; }