Common in remote communication, lazy initialization, and secure hardware access.
- Controls access
- Adds security, caching, lazy loading
C Example
#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
#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;
}