Proxy Design Pattern
Proxy design pattern is used to provide a placeholder for an object to control its access.
The intent is to provide a placeholder for another object and control its access.
- Provide a surrogate or placeholder for another object to control access to it.
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.
- Need to defer the instantiation of object until it is 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.
- Come up with another Proxy class which acts for real class and instantiates the object of real class when required.
Where it 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.
How they work together?
- 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.
- 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.
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 is from his courses on design patterns.
Design Patterns in Java