Proxy Design Pattern in Java

The Proxy is known as a structural pattern, as it is used to form large object structures across many disparate objects. It functions as an interface to something else such as a network connection, a large object in memory, a file, or some other resource that is expensive or impossible to duplicate.

For more information on usage or for below use cases you can refer to http://en.wikipedia.org/wiki/Proxy_pattern

Use Cases

Remote Proxy – Represents an object locally which belongs to a different address space. Take an example of ATM machine, it will hold proxy objects for bank information that exists in the remote server.

Virtual Proxy – In place of a complex or heavy object, use a skeleton representation. When an underlying image is huge in size, just represent it using a virtual proxy object and on demand load the real object. You feel that the real object is expensive in terms of instantiation and so without the real need we are not going to use the real object. Until the need arises we will use the virtual proxy.

Protection Proxy – An MNC where the proxy server that provides us internet by restricting access to some sort of websites like public e-mail, social networking, data storage etc. and provides only work related web pages. This is a type of proxy design pattern.

Example

The real world example would be a cheque or a debit card or a credit card is proxy for what is in our bank account. It can be used in place of cash and provides a mean for accessing that cash when required. And that is exactly what the Proxy pattern does – controls and manages access to the object they are protecting.

Another example would be when we generate client for Soap Web Service. A part of it contains implementation of proxy design pattern. The client has the stub files generated which acts as a proxy for classes in server side.

Class Diagram

Proxy Pattern in Java
Implementation

Create an Interface

Create an implementation class

Create a proxy class

Create another class for authenticate service. Real world application will have more concrete implementation

Run the above class ProxyPatternTest and see the below output

Output 

That’s all. Thanks for your reading.

Soumitra

Software Professional, I am passionate to work on web/enterprise application. For more information please go to about me. You can follow on Twitter. You can be a friend on Facebook or Google Plus or Linkedin

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.