The Proxy design pattern is one of the complicated design pattern , which is critical to understand and once you understand it’s simple and straight froward. For senior level of interview it asked frequently.
“Provides a surrogate or placeholder for another object to control access to it.”
Proxy holds a reference of real object, we can say in some cases proxy is responsible to create and destroy of object. Client not interact directly to real object , it call via proxy object.
why actually required this proxy? is this just because of control. yes, somewhere control is the game of creating proxy.
Control may be needed:
– if remote machine
– if expensive to create an object
– if protection/security is required.
Proxy pattern used for: control access to another object, which may be remote, expensive to create or in need of securing.
Different type of Proxy
- 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.
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.
Key Points of Proxy
- 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.
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.
Usage of Proxy
It can be used in:
- Virtual Proxy scenario
- Protective Proxy scenario
- Remote Proxy scenario
- Smart Proxy scenario
Suggestions are welcome to improve this post.