C++代理模式

主要根据代理模式整理,感谢作者分享!

[DP]上的定义:为其他对象提供一种代理以控制对这个对象的访问。有四种常用的情况:(1)远程代理,(2)虚代理,(3)保护代理,(4)智能引用。本文主要介绍虚代理和智能引用两种情况。

考虑一个可以在文档中嵌入图形对象的文档编辑器。有些图形对象的创建开销很大。但是打开文档必须很迅速,因此我们在打开文档时应避免一次性创建所有开销很大的对象。这里就可以运用代理模式,在打开文档时,并不打开图形对象,而是打开图形对象的代理以替代真实的图形。待到真正需要打开图形时,仍由代理负责打开。这是[DP]一书上的给的例子。下面给出代理模式的UML图。

 #include <bits/stdc++.h>
//#include "solution.h"
using namespace std; #define debug(x) cout << #x << " at line " << __LINE__ << " is: " << x << endl class CImage
{
public:
virtual ~CImage(){cout << "~CImage()\n";}
virtual void Show(){}
protected:
CImage(string imgName): m_imgName(imgName){cout << "CImage()\n";}
string m_imgName;
}; //concrete implement
class CBigImage : public CImage
{
public:
CBigImage(string imgName): CImage(imgName), m_bigImgName(imgName){
cout << "CBigImage()\n";
}
~CBigImage(){
cout << "~CBigImage()\n";
}
void Show(){cout << "show big image" <<endl;}
protected:
string m_bigImgName;
}; // proxy
class CBigImageProxy : public CImage
{
public:
CBigImageProxy(string imgName): CImage(imgName), m_img(NULL), m_bigImgName(imgName){
cout << "CBigImageProxy()\n";
}
~CBigImageProxy(){
if(NULL != m_img){
delete m_img;
m_img = NULL;
}
cout << "~CBigImageProxy()\n";
}
void Show(){
if(NULL == m_img){
m_img = new CBigImage(m_bigImgName);
}
m_img->Show();
}
private:
CImage *m_img;
string m_bigImgName;
}; class Subject
{
public:
virtual ~Subject(){cout << "~Subject()\n";}
virtual void Request()=;
protected:
Subject(){cout << "Subject()\n";}
}; class ConcreteSubject : public Subject
{
public:
ConcreteSubject(){
cout << "ConcreteSubject()\n";
}
~ConcreteSubject(){
cout << "~ConcreteSubject()\n";
}
virtual void Request(){cout << "ConcreteSubject Request()\n";}
}; class Proxy : public Subject
{
public:
Proxy(){
cout << "Proxy()\n";
this->m_sub = new ConcreteSubject();
}
// Proxy(Subject* _sub):m_sub(_sub){
// cout << "Proxy(Subject)\n";
// } virtual void Request()//实现对委托者的委托任务执行与补偿
{
this->m_sub->Request();
}
~Proxy(){
if(NULL != this->m_sub){
delete this->m_sub;
this->m_sub = NULL;
}
cout << "~Proxy()" << endl;
} private:
Subject *m_sub;
}; int main(int argc, char *argv[])
{
CBigImageProxy *bip = new CBigImageProxy("proxy.jpg");
bip->Show();
delete bip;
bip = NULL; Proxy *py = new Proxy();
py->Request();
delete py;
py = NULL;
return ;
}
// g++ -g -Wall main.cpp -o xmain

两个代理模式的示例

C++代理模式

至于智能指针,建议可以参考C++11标准的智能指针。

上一篇:2016.7.5 如何在maven中添加所需依赖(只知道jar包的部分名字的情况)


下一篇:maven中添加json-lib的jar包