Proxy Design Pattern in Java

As the name of the pattern suggests, Proxy Design Pattern is a structural design pattern that is frequently used in JAVA to fill in for something. In most cases, a proxy object fills in for a real object as a substitute. Proxy objects have the power to perform certain basic operations before they connect a client to a real object. Though this pattern is rarely used in mainstream applications, it comes in handy when you have to save memory as well as manipulate object access. Classes also act as proxy interfaces.

Definition

The Proxy design pattern allows a class to act as an intermediary interface for another program or resource. The pattern also caters to class complexity abstraction.

Example and Code

For this example, let us consider a document finder that fetches a document when a directory input is feeded to it. Through this simple code we will get a clearer picture of how a normal class and a proxy class implements the original interface.

/*Let us start by defining a document finder interface*/

public interface DocuFinder {
public void getDocu();
}

//Let us implement this interface to a real class

public class RealDocuFinder implements DocuFinder {
public RealDocument (URL dir) {
loadDocument(url);
public void getDocument()     //display the document
}
}

//Implementing the proxy class

public class ProxyDocuFinder implements DocuFinder {
private URL dir;
public ProxyDocument (URL dir)
this.dir = dir;

public displayDocument()
{….}                                                        //display relevant document
}

When to use Proxy Design Pattern

This design pattern is typically used when a client wants developers to add some functionality or attributes to a certain object of class but does not however want the source code altered. In such cases, a proxy interface is introduced with the added features that will then connect clients to the service (main) interface. In practice, a proxy method must always refer to a real object as their main purpose is to delegate work but by taking up less memory.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.