Proxy Design Pattern Explained with C++ Sample

Proxy design pattern is otherwise known as surrogate design pattern.It is used to control and manage access to an object.

following are the actors in a proxy pattern

1)Real subject implementing the subject interface
2)Proxysubject implementing the subject interface and control access to the realsubject then delegate calls to it

client will be using proxy class; proxy then delegates calls to realsubject class.

some of the applications of proxy pattern is

1) provide user authentication to an action defined in a class ;
users can define a proxy class and define the user validation logic there , then delegates call to real class if authentication succeeds.
2)If I want to make action in a class thread safe (if client needs thread safety) .Define a proxy class and write the thread safety logic in that class and delegate the call to real object .client will be using the proxy class.

class diagram is shown below

sample source code is below


// ProxyPatternSample.cpp : This file contains the 'main' function. Program execution begins and ends there.
//

#include "pch.h"
#include <iostream>
using namespace std;
class IBox
{
public:
	virtual void Open() = 0;
	virtual ~IBox() {};
};

class SimpleBox : public IBox
{
public:
	virtual void Open()
	{
		cout << "Opening te box";
	}
};


class ProxyBox : public IBox
{
public:
	ProxyBox(string sUserName, string sPwd):m_UserName(), m_Pwd(sPwd)
  
	{

	}

	virtual void Open()
	{
		if (iSAuthenticated()) {
			cout << "\nAuthentication Success";
			m_Box.Open();
		}
		else
			cout << "\nAuthentication Failure , You can't open the Box";
	}
private:
	bool iSAuthenticated()
	{
		bool bAuthenticated = false;
		//bAuthenticated = AUthenication logic here
		return bAuthenticated;

	}
private:
	string m_UserName;
	string m_Pwd;
	SimpleBox m_Box;
};

int main()
{
	IBox* box = new ProxyBox("Admin", "Test123");
	box->Open();
	delete box;
}

Sample source code implemented in vs 2017 is available in Git repository: download