StructuralC++verifiedVerified

Proxy Pattern in C++

Provides a surrogate or placeholder for another object to control access, add lazy initialization, caching, logging, or access control.

How to Implement the Proxy Pattern in C++

1Step 1: Define the Subject interface

class Image {
public:
    virtual ~Image() = default;
    virtual void display() = 0;
};

2Step 2: Real subject (expensive to create)

class RealImage : public Image {
    std::string filename_;
public:
    explicit RealImage(std::string name) : filename_(std::move(name)) {
        std::cout << "Loading " << filename_ << " from disk...\n";
    }
    void display() override {
        std::cout << "Displaying " << filename_ << "\n";
    }
};

3Step 3: Proxy delays loading until display() is called

class ImageProxy : public Image {
    std::string filename_;
    std::unique_ptr<RealImage> real_;
public:
    explicit ImageProxy(std::string name) : filename_(std::move(name)) {}

    void display() override {
        if (!real_) real_ = std::make_unique<RealImage>(filename_);
        real_->display();
    }
};

int main() {
    ImageProxy img("photo.jpg");
    std::cout << "Image created (not loaded yet)\n";
    img.display(); // loads now
    img.display(); // uses cached
}

Proxy Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Proxy Pattern in the Real World

A corporate receptionist acts as a proxy for the CEO. When someone wants to meet the CEO, the receptionist checks credentials, schedules the meeting, and logs the visit before granting access. The visitor interacts with the receptionist using the same protocol they would use with the CEO—the receptionist simply adds control and record-keeping around that access.