The Proxy design pattern provides a surrogate or place holder for another object to control access to it. types: virtual proxy, remote proxy, Protection Proxy…
1. Overview of Proxy Design Pattern
“Provides a surrogate or placeholder for another object to control access to it.”
The Proxy design pattern is one of the complicated design patterns, which is a little bit tricky to understand, and once you understand it’s simple and straightforward. For the mid-level or senior-level of the interview, it asked frequently.
Proxy holds a reference of a real object, we can say in some cases proxy is responsible to create and destroy of the object. The client does not interact directly with a real object, it calls via proxy object.
why actually required this proxy? is this just because of control. yes, somewhere control is the game of creating proxy.
2. why control needed in Proxy Pattern
- if remote machine
- if expensive to create an object
- if protection/security is required.
3. Intent of Proxy Pattern
Proxy pattern used for: control access to another object, which may be remote, expensive to create or in need of securing.
4. Different type of Proxy Pattern
- Remote Proxy: control access to remote object. proxy act as local representative of an object which lives in another JVM. When we call method, proxy get call which in turns call remotely to remote object by transferring call over the wire. Proxy returns result to client.
- virtual Proxy: control access to a resource which is expensive to create. it act as a representative for an object which might be expensive to create.. Once Virtual proxy created they in turns request to real object.
- Protection Proxy: control access to a resource based on access right.
- Although , there are more types i.e. firewall proxy, caching proxy, synchronization proxy etc.. But for this post rest are out of scope.
5. Similar Design Pattern
All the followings wraps object but intent of wrapping object are different. Let us see following as :
- Decorator: it wraps an object to add additional behavior at run time.
- Facade : it wraps objects to simplify the interface.
- Adapter: wraps to object to make compatible of interface.
6. Key Points of Proxy Pattern
- Proxy and Decorator are similar in structurally , but intent of both are different. one controlling access while another adding responsibility.
- Similar to any wrapper, proxy increases number of classes and objects in design .
- Remote proxy manage communication interaction between client and real object
- Virtual proxy taking access control of an object if expensive to instantiate.
7. Advantage of Proxy
Proxy design pattern provides the protection to the original object from outside world. Here, what is meaning of protection, it means, no one/client access directly to target object.
8. Usage of Proxy
Proxy pattern can be used in:
- Virtual Proxy scenario
- Protective Proxy scenario
- Remote Proxy scenario
- Smart Proxy scenario