设计模式--结构型模式--代理模式

#include "stdafx.h"
#include
#include
#include
#include
#include

using namespace std;
//Structural Patterns--Proxy 
//结构型模式--代理模式

//Subject(抽象主题):声明了 RealSubject 与 Proxy 的共同接口,定义了某个/些功能。
//RealSubject(真实主题):通常执行具体的业务逻辑,Proxy 控制对它的访问。
//Proxy(代理):持有一个 RealSubject 引用(指针),可以在需要时将请求转发给 RealSubject,以此起到代理的作用。

//---------------------------------------------------------------
//一.虚拟(virtual)代理
//---------------------------------------------------------------

//Subject(抽象主题)
class Image
{
public:
    Image(std::string name):m_strImageName(name){}
    virtual ~Image(){}
    virtual void Show() = 0;
protected:
    std::string m_strImageName;
};

//RealSubject(真实主题)
class BigImage : public Image
{
public:
    BigImage(std::string name):Image(name){}
    ~BigImage(){}
    void Show(){cout<<"show big image : "< };

//Proxy(代理)
class BigImageProxy : public Image
{
public:
    BigImageProxy(std::string name):Image(name),m_pBigImage(NULL){}
    ~BigImageProxy(){}
    void doSomethingBefore(){cout<<"BigImageProxy doSomethingBefore." << endl;}
    virtual void Show()
    {
        if(m_pBigImage == NULL) m_pBigImage = new BigImage(m_strImageName);//延迟
        doSomethingBefore();
        m_pBigImage->Show();
        doSomethingAfter();
    }
    void doSomethingAfter(){cout<<"BigImageProxy doSomethingAfter." << endl;}
private:
    BigImage *m_pBigImage;
};

//----------------------------------------------------------
//测试
void pdProxyTestMain()
{
    Image *pImage = new BigImageProxy("proxy.jpg");
    pImage->Show();
    
    if(pImage != NULL) {delete pImage ; pImage = NULL;}
    return;
}

你可能感兴趣的:(设计模式)