Most of us have used a proxy server to access the internet. An HTTP proxy server is essentially a server on our campus, that controls all the HTTP requests made to the outside world. An HTTP request that I make from my PC bangs on the proxy server, which verifies its sanity and then makes the call on my behalf. It then verifies the sanity of the HTTP response and returns it back to me. It gives me a feeling that I am connected to the internet. But in reality, I am only connected to the proxy server.
The proxy design pattern does just that. The proxy object provides a kind of transparent wall between the caller and the callee. In the code, this is pretty similar to the adapter or decorator patterns. But the design concept is very different. The adapter is used to alter an interface and the decorator is used to add value. But the proxy pattern does neither of these. It is just transparent.
Then what does it do? What is the great deal we achieve by implementing a proxy? A proxy class can be used in one or more of the following scenarios:
- A virtual proxy is a placeholder for "expensive to create" objects. The real object is only created when a client first requests/accesses the object. Until then, the proxy server handles the show.
- A remote proxy provides a local representative for an object that resides in a different address space. This provides a single gateway for the external communications. It can also help reduce unnecessary remote invocations by responding to requests that can be locally available.
- A protective proxy controls access to a sensitive master object. The "surrogate" object checks that the caller has the access permissions required prior to forwarding the request.
- A smart proxy interposes additional actions when an object is accessed. Typical uses include memory management (ensure objects are freed when not required), thread management(ensure lock on the sensitive object)
The Proxy pattern has the following roles:
- Client: The object that invokes a method
- Subject: An interface that defines the method to be invoked on the proxy and the real subject
- Proxy: The concrete class that implements the Subject interface and takes care of passing the invocation to the real subject
- Real Subject: The real code that hides behind the proxy.