C++ Proxy Pattern Example

In this article, we will learn how to use and implement the Proxy Pattern in C++ with an example.

Proxy is a structural design pattern that lets you provide a substitute or placeholder for another object. A proxy controls access to the original object, allowing you to perform something either before or after the request gets through to the original object.

C++ Proxy Pattern Example

The below diagram shows the generic structure of the Proxy Pattern:

Let's refer to the above structure to create an example to demonstrates the usage of the Proxy Pattern.
#include <iostream>

/*
 * Subject
 * defines the common interface for RealSubject and Proxy
 * so that a Proxy can be used anywhere a RealSubject is expected
 */
class Subject
{
public:
    virtual ~Subject() {
        /* ... */
    }

    virtual void request() = 0;
};

/*
 * Real Subject
 * defines the real object that the proxy represents
 */
class RealSubject : public Subject
{
public:
    void request()
    {
        std::cout << "Real Subject request" << std::endl;
    }
};

/*
 * Proxy
 * maintains a reference that lets the proxy access the real subject
 */
class Proxy : public Subject
{
public:
    Proxy()
    {
        subject = new RealSubject();
    }

    ~Proxy()
    {
        delete subject;
    }

    void request()
    {
        subject->request();
    }

private:
    RealSubject *subject;
};


int main()
{
    Proxy *proxy = new Proxy();
    proxy->request();

    delete proxy;
    return 0;
}

Output

Real Subject request
Use this pattern whenever there is a need for a more versatile or sophisticated reference to an object than a simple pointer.

Related C++ Design Patterns