设计模式C++描述----13.代理(Proxy)模式

来源:互联网 发布:linux权限不够 编辑:程序博客网 时间:2024/05/22 07:41

一. 举例说明

我们有时打开一个网站时会发现有这样的现象,网站上的文字都显示出来了,但是上面的图片还没显示,要等一会才能显示。

这些未打开的图片的位置上,还是会有图片框和一些等待的信息的,这就是代理模式的应用,此时的代理存储了真实图片的路径和尺寸也用来显示一些友好的信息。

结构图如下:



代码实现:
//基类class BigImage{public:    BigImage(string name): m_imageName(name) {}    virtual ~BigImage() {}        virtual void Show() {}protected:      string m_imageName;};//真实类class RealBigImage: public BigImage  {public:    RealBigImage(string name):BigImage(name) {}    ~RealBigImage() {}        void Show()    {        cout<<"Show big image : "<<m_imageName<<endl;    }};//代理class Proxy: public BigImage  {private:      RealBigImage *m_bigImage;public:      Proxy(string name):BigImage(name),m_bigImage(0)    {}     ~Proxy()    {        delete m_bigImage;    }        void Show()    {          if(m_bigImage == NULL)        {            cout<<"please wait ..."<<endl;            m_bigImage = new RealBigImage(m_imageName); //代理创建真实对象        }        m_bigImage->Show();      }  };  int main()  {      BigImage *image = new Proxy("SomeBigPic.jpg"); //使用代理        image->Show(); //代理的操作        delete image;        return 0;  }

说明:

BigImage:虚基类,定义了 RealBigImage 和 Proxy 的共用接口,这样就在任何使用 RealBigImage 的地方都可以使用 Proxy。

RealBigImage:定义Proxy所代表的真实实体。

Proxy:通过代理访问实体。

二. 代理模式

定义:为其他对象提供一种代理以控制对这个对象的访问


代理模式分为四种情况:(1)远程代理,(2)虚代理,(3)保护代理,(4)智能引用。

上文介绍的是虚代理,虚代理是当创建开销很大时,通过代理来存放需要很长时间的真实对象。

代理模式的要点:

1. 代理模式与真实对象有同样的接口,这样保证在任何使用 RealSubject 的地方都可以使用 Proxy

2. Proxy 保存一个真实象的引用,这样可以访问 RealSubject 对象。


原创粉丝点击