Proxy Pattern

Sometimes, instead of using an object directly, it is beneficial to use a placeholder for that object. A client invokes the methods of this placeholder. The placeholder in turn forwards the calls to the target object.

The proxy pattern provides a placeholder or surrogate object that stands in for the target object and thus controls the access to it.

A proxy is basically a substitute for an intended object. When a client deals with a proxy object, it thinks that it is dealing with the actual object. We need this kind of design because dealing with an original object is not always possible.

Below are few scenarios proxy pattern can be used:

  • When we want to have controlled access to the target object and to achieve that we route all calls through a placeholder (proxy)

  • When we want to hide the creation and configuration process of the target object from the client due the complexities involved.

  • When we want to dynamically change the target object without affecting the client code.

  • Sometimes the target object is not going to be available at development time and our application can connect with the target only at runtime.

  • The service proxies used by ASMX and WCF services are based on the proxy pattern and are used to control and simplify access to the underlying service.

The Target class implements the ITarget interface, and its Operation() method contains the code that performs the actual work.

The Proxy class also implements ITarget to mimic the Target object.

Client will instantiate the Proxy and will invoke the operations of the Proxy

Responsibility of Operation() method of the Proxy is to forward the call to the Operation() method of the Target.