C++

Proxy Pattern – Behavioral – C++

A proxy is a wrapper or agent object that is being called by the client to access the real serving object, this is achieved because both the proxy and the real object implement the same interface.

Example C++

class IPerson {
public:
  virtual void Drive() = 0;
};

class Person : public IPerson{
  void Drive() override {
    std::cout << "Person Drove" << std::endl;
  }
};

class ProxyPerson : public IPerson {
private:
  IPerson* realPerson;
  int _age;

public:
  ProxyPerson (int age) : realPerson(new Person()), _age(age) {}
  ~ProxyPerson () {
    delete realPerson;
  }

  void Drive() {
    if (_age > 16)
      realPerson->Drive();
    else
      std::cout << "Sorry, the person is too young to drive." << std::endl;
  }
};

 int main()
{
    IPerson* person = new ProxyPerson(16);
    person->Drive();
    delete person;

    person = new ProxyPerson(25);
    person->Drive();
    delete person;
}