Design Pattern means that “we had some problem then we found the solution and gave name to this solution” and proxy is also one of the solution so we need to find the problem that proxy has solved and how ?
This design pattern comes under Structural Category .
================================================================
Proxy Design pattern provides a placeholder for another object and control the access to it. It comes under Structural Design pattern. It adds extra functionalities before or after actual request or operation on actual object.
Class Diagram:
Proxy Design Pattern Example with Source Code in C++:
File Name: proxy.cpp
/* * File:proxy.cpp * This file is described the Proxy Design Pattern with help of example * Author: Aplha * Date: 29 Dec 2020 */ //Header file #include<iostream> //Subject Interface class ISubject { public: virtual void Request() = 0; }; // Real Subject class RealSubject:public ISubject { public: void Request() { std::cout<<"Real Object Request Handler"<<std::endl; } }; //Proxy Class class Proxy:public ISubject { RealSubject* m_RealSub; void ExtraCheck() { std::cout<<"Proxy Extra Check, adding Extra Functionalities"<<std::endl; } public: void Request() { std::cout<<"Proxy Object Request Handler"<<std::endl; ExtraCheck(); m_RealSub->Request(); } public: Proxy() { m_RealSub = new RealSubject; } ~Proxy() { if(m_RealSub) delete m_RealSub; } }; //Client int main() { std::cout<<"**********Proxy Design Patter**********"<<std::endl; std::cout<<"**********Calling Real Subject Directly********"<<std::endl; ISubject * sub = new RealSubject; sub->Request(); delete sub; std::cout<<"***********Calling Proxy Directly***************"<<std::endl; ISubject * sub1 = new Proxy; sub1->Request(); delete sub1; return 0; }
Compilation:
g++ -std=c++11 proxy.cpp
Output:
**********Proxy Design Patter**********
**********Calling Real Subject Directly********
Real Object Request Handler
***********Calling Proxy Directly***************
Proxy Object Request Handler
Proxy Extra Check, adding Extra Functionalities
Real Object Request Handler