proxy 模式示例

#include "Publicinc.hpp"

class  Image
{
public:
    virtual   ~Image()
    {
    }

    virtual   void  Display() = 0;
};

class  RealImage : public Image
{
public:
    RealImage(const string& filePath)
        : m_filePath(filePath)
    {
        loadFromDisk(m_filePath);
    }

    virtual  void  Display()
    {
        printf("Display %s\n", m_filePath.c_str());
    }

private:
    void  loadFromDisk(const string& file)
    {
        printf("Loading %s\n", file.c_str());
    }


private:
    string  m_filePath;
};


class  ProxyImage : public  Image
{
public:
    ProxyImage(const string& filePath)
        : m_image(nullptr)
        , m_filePath(filePath)
    {
    }

    virtual  void  Display()
    {
        if (nullptr == m_image) {
            m_image = new  RealImage(m_filePath);
        }

        m_image->Display();
    }

private:
    RealImage*  m_image;
    string  m_filePath;
};

void  TestProxyImage()
{
    Image* image = new  ProxyImage("test_10mb.jpg");

    image->Display();

    image->Display();
}

你可能感兴趣的:(C++)