Proxy design pattern is used to provide a placeholder for an object to control its access.
Intent
Provide a surrogate or placeholder for another object to control access to it.
The intent of proxy design pattern is to provide a placeholder for another object and control its access.
Problem
Need to defer the instantiation of object until it is required.
Sometimes object creation and initialization may be very costly affair and may affect performance, so it is better to defer
the instantiation until it is required.
Solution
Come up with another Proxy class which acts for real class and instantiates the object of real class when required.
So we can have another class called proxy which will be placeholder for real class and will instantiate the object of Real
class when it is actually required.
Where proxy design pattern is applicable?
The cost of object instantiation is high.
Another object is required to present an object in different address space called as remote proxy.
There is access control required for an object, called as protection proxy.
Proxy Design Pattern UML Structure
Participant classes of proxy design pattern
Subject class provides the interface Request().
Proxy class works as place holder for RealSubject. It has instance of class RealSubject, so it creates the
object of RealSubject and uses the method of RealSubject. It can instantiate when operation is required on RealSubject;
and can provide access control too on RealSubject object. Proxy implements the interface which is provided by Subject.
RealSubject has actual functionality implementation of the interface provided by Subject. Proxy presents as
place holder for RealSubject.
How they work together?
Client uses the Subject interface and proxy works as place holder for RealSubject to avoid the high cost of
instantiation. When any operation is invoked, then only proxy instantiates the object of RealSubject and then proxy uses
the methods of RealSubject inside its methods to get the functionality done.
So we can see proxy is able to defer the instantiation and provide a way to apply access control on RealSubject.
Proxy Design Pattern Example
Here is the proxy design pattern example.
Debugger requires Autos/Callstack to show all the variables and functions. But loading all of them will be very expensive,
so load them only when requested.
Suresh Kumar Srivastava is founder of online learning site coursegalaxy.com and author of popular books C In Depth,
Data Structures Through C In Depth. He has 18+ years experience in industry and worked on architecture and design of
multiple products. This article Proxy Design Pattern is from his Design Patterns course.