意图:
为其他对象提供一种代理以控制这个对象的访问
适用性:
1远程代理:为一个对象在不同的地址空间提供局部代表
2虚代理:根据需要创建开销很大的对象
3保护代理:控制对原始对象的访问,保护代理用于对象应该有不同的访问权限的时候
4智能指针:
1对指向实际对象的引用计数,当该对象没有引用时,可自动释放
2当第一次引用一个持久对象时,将它装入内存
3在访问第一个对象前,检查是否已经锁定,以确保其他对象不能改变它
效果:
Proxy模式在访问对象时引入了一定程度的间接性。根据代理的类型,附加的间接性有多种用途:
1 Remote Proxy可以隐藏一个对象存在于不同地址空间的事实
2 Virtual Proxy 可以进行最优化,根据要求创建对象
3 Protection Proxy和Smart Proxy都允许在访问一个对象时有一些附加的内务处理
4 隐藏Copy-on-write,如果拷贝没有被修改,开销没有必要。用代理延迟拷贝过程,只有当这个对象被修改的时候才对它进行copy
实现:
1重载C++中的存取运算符
2 Proxy不需要知道具体的实体类型
示例代码
Proxy.h
- #include <iostream>
- #include <string>
- using namespace std;
- class Point
- {
- public:
- Point():_x(0),_y(0)
- {
- cout<<"X is 0 and Y is 0"<<endl;
- }
- Point(int i,int j):_x(i),_y(j)
- {
- cout<<"X is "<<_x<<" and Y is "<<_y<<endl;
- }
- int _x;
- int _y;
- };
- class Graphic
- {
- public:
- Graphic() {cout<<"A Graphic is created"<< endl;}
- virtual ~Graphic() {cout<<"A Graphic is deleted"<< endl;}
- virtual void Draw(const Point& at)
- {
- cout<<"Draw the Graphic on X="<<at._x<<" Y="<<at._y;
- }
- char* GetImageName()
- {
- return _fileName;
- }
- protected:
- char* _fileName;
- };
- class Image:public Graphic
- {
- public:
- Image(const char* file)
- {
- _fileName = strdup(file);
- cout<<"Generate a Image with file name is "<<_fileName <<endl;
- }
- virtual ~Image()
- {
- cout<<"Destory a Image with file name is "<<*_fileName <<endl;
- delete _fileName;
- _fileName = 0;
- }
- virtual void Draw(const Point& at)
- {
- cout<<"Draw the Image on X="<<at._x<<" Y="<<at._y;
- }
- };
- class ImageProxy:public Graphic
- {
- public:
- ImageProxy(const char* imageFile);
- virtual ~ImageProxy();
- //virtual void Draw(const Point& at);
- Image* GetImage();
- private:
- Image* _image;
- char* _filename;
- };
- class TextDocument
- {
- public:
- TextDocument();
- void Insert(Graphic*);
- };
Proxy.cpp
- #include "Graphic.h"
- #include <string>
- #include <iostream>
- using namespace std;
- ImageProxy::ImageProxy(const char *Imagefile)
- {
- _filename = strdup(Imagefile);
- _image = 0;
- cout<<"Create an Image Proxy;"<<endl;
- }
- ImageProxy::~ImageProxy()
- {
- delete _filename;
- delete _image;
- cout<<"Destroy an Image Proxy;"<<endl;
- }
- Image* ImageProxy::GetImage()
- {
- if (_image == 0)
- {
- _image = new Image(_filename);
- }
- return _image;
- }
- TextDocument::TextDocument()
- {
- cout<<"Create an Text Document"<<endl;
- }
- void TextDocument::Insert(Graphic* g)
- {
- cout<<"Insert an Image in TextDocument"<<endl;
- }
main.cpp
- #include <iostream>
- #include "Graphic.h"
- using namespace std;
- int main()
- {
- TextDocument a;
- ImageProxy* b = new ImageProxy("filename");
- a.Insert(b);
- Image* c;
- c = b->GetImage();
- Point d(2,3);
- return 0;
- }