Proxy (Design Pattern)

This structural pattern controls the access to a class.



Looks similar to a decorator, but it instantiates the object by itself (composition).


#include <memory>
#include <iostream>
 
class IPictureReader {
public:
    virtual void load(std::string name) = 0;
};
 
class PictureReader : public IPictureReader {
public:
    void load(std::string name) {
        std::cout << "Loading the actual image." << std::endl;
        // ...
    }
};
 
class PictureReaderProxy : public IPictureReader {
public:
    PictureReaderProxy() : m_Picture(new PictureReader()) {}
 
    void load(std::string name) {
        if (m_Name != name) {
            m_Picture->load(name);
            m_Name = name;
        }
    }
private:
    std::string m_Name;
    std::unique_ptr<IPictureReader> m_Picture;
};
 
int main() {
    std::unique_ptr<IPictureReader> picProxy(new PictureReaderProxy());
    picProxy->load("img001.jpg"); // loads the new picture
    picProxy->load("img001.jpg"); // uses the cached picture
    // ...
    return 0;
}