DP: Proxy

Proxy provides a placeholder or surrogate for another object to control access to it. It can delay creation, control permissions, or add logging.

Common in remote communication, lazy initialization, and secure hardware access.

  • Controls access
  • Adds security, caching, lazy loading

C Example

c
#include <stdio.h>

void realSensorRead() {
    printf("Reading sensor\n");
}

void proxyRead(int authorized) {
    if (authorized)
        realSensorRead();
    else
        printf("Access denied\n");
}

int main() {
    proxyRead(1);
}

C++ Example

cpp
#include <iostream>
using namespace std;

class Sensor {
public:
    virtual void read() = 0;
};

class RealSensor : public Sensor {
public:
    void read() override {
        cout << "Reading sensor\n";
    }
};

class SensorProxy : public Sensor {
    RealSensor real;
    bool authorized;
public:
    SensorProxy(bool auth) : authorized(auth) {}
    void read() override {
        if (authorized)
            real.read();
        else
            cout << "Access denied\n";
    }
};

int main() {
    Sensor* s = new SensorProxy(true);
    s->read();
    delete s;
}