Proxy
1. Usage
Proxy pattern in general is Wrapper. Sometimes its hard/impossible to modify real object. For client using Proxy object should be same like using real object as they share same interface.
Consider following usage scenarios:
- Remote Proxy - in distributed communication we create local proxy object which hide all communication with remote object
- Virtual Proxy - handles situations when object is expensive to create.(lazy initialization)
- Protection Proxy - Wrapper of extra protection measures around real object
- Smart proxy - adds extra operations when object is accessed.
While adapter bridges the gap between two classes - proxy provides a surrogate to control the access to the real object
2. UML class diagram
3. Pros
- More maintainable if number of usage of object more then 4-5
- More control over method calls.
- More robust as only constructed object will be available to client
4. Cons
- Code duplication needs to copy all fields from original object.
5. Source code
#include <iostream>
using namespace std;
class ICar {
public:
virtual void DriveCar() = 0;
};
class Car : public ICar {
public:
void DriveCar() {
cout << "Driving Car!" << endl;
}
private:
ICar* _pImpl;
};
class ProxyCar : public ICar {
public:
ProxyCar(int driver_age) : _driver_age(driver_age) {
_pImpl = new Car();
}
void DriveCar() {
if (_driver_age >= 16){
_pImpl->DriveCar();
}else{
cout << "Driving car for under age not allowed." << endl;
}
}
private:
ICar* _pImpl;
int _driver_age;
};
int main()
{
ICar * car = new ProxyCar(14);
car->DriveCar();
car = new ProxyCar(21);
car->DriveCar();
return 0;
}
