Proxy

Originally published 2016-02-28 · Boris Ivanov

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:

While adapter bridges the gap between two classes - proxy provides a surrogate to control the access to the real object

2. UML class diagram

proxy

3. Pros

4. Cons

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;
}