4

Gang of Four – Proxy Design Pattern

Design Pattern LogoDescription:

Proxy is another Structural design pattern which works ‘on behalf of’ or ‘in place of’ another object in order to access the later.

When to use this pattern?

Proxy pattern is used when we need to create a wrapper to cover the main object’s complexity from the client.

What are the usage scenarios?

  • Virtual Proxy – Imagine a situation where there is multiple database call to extract huge size image. Since this is an expensive operation we can possibly use the proxy pattern which would create multiple proxies and point to the huge size memory consuming object for further processing. The real object gets created only when a client first requests/accesses the object and after that we can just refer to the proxy to reuse the object. This avoids duplication of the object and hence saving memory.
  • Remote Proxy – A remote proxy can be thought about the stub in the RPC call. The remote proxy provides a local representation of the object which is present in the different address location. Another example can be providing interface for remote resources such as web service or REST resources.
  • Protective Proxy – The protective proxy acts as an authorisation layer to verify if the actual user has access to appropriate content. An example can be thought about the proxy server which provides restrictive internet access in office. Only the websites and contents which are valid will be allowed and the remaining ones will be blocked.
  • Smart Proxy – A smart proxy provides additional layer of security by interposing specific actions when the object is accessed. An example can be to check if the real object is locked before it is accessed to ensure that no other object can change it.

Structure:

Proxy Design Pattern Structure

Proxy Design Pattern Structure

Participants:

  • Subject – This object defines the common interface for RealSubject and Proxy so that a Proxy can be used anywhere a RealSubject is expected.
  • Proxy – It maintains a reference to the RealSubject so that Proxy can access it. It also implements the same interface as the RealSubject so that Proxy can be used in place of RealSubject. Proxy also controls the access to the RealSubject and can create or delete this object.
  • RealSubject – This refers the main object which the proxy represents.

Example:

We will discuss two examples in this article. The first one will be virtual proxy pattern and the other one for protection proxy pattern.

Virtual Proxy Example:

As mentioned earlier virtual proxy is useful to save expensive memory resources. Let’s take a scenario where the real image contains a huge size data which clients needs to access. To save our resources and memory the implementation will be as below:

  • Create an interface which will be accessed by the client. All its methods will be implemented by the ProxyImage class and RealImage class.
  • RealImage runs on the different system and contains the image information is accessed from the database.
  • The ProxyImage which is running on a different system can represent the RealImage in the new system. Using the proxy we can avoid multiple loading of the image.

Class Diagram:

Virtual Proxy Example

Virtual Proxy Example

Code Example:

Image.java

public interface Image {
	public void showImage();
}

RealImage.java

public class RealImage implements Image {

	private String fileName = null; 
	public RealImage(String strFileName){
		this.fileName = strFileName;
	}
	@Override
	public void showImage() {
		System.out.println("Show Image:" +fileName);

	}
}

ProxyImage.java

public class ProxyImage implements Image {
	private RealImage img= null;
	private String fileName = null;

	public ProxyImage(String strFileName) {
		this.fileName = strFileName;
	}
	/*
	 * (non-Javadoc)
	 * @see com.proxy.virtualproxy.Image#showImage()
	 */
	@Override
	public void showImage() {
		if(img == null){
			img = new RealImage(fileName);
		}
		img.showImage();
	}
}

Client.java

public class Client {
public static void main(String[] args) {
 final Image img1 = new ProxyImage("Image***1");
 final Image img2 = new ProxyImage("Image***2");
 img1.showImage();
 img2.showImage();
	}
}

Protection Proxy Example:

  • Let’s assume that company ABC starts a new policy that employees will now be prohibited internet access based on their roles. All external emails websites will be blocked. In such situation we create InternetAccess interface which consists of operation grantInternetAccess().
  • The RealInternetAccess class which allows of internet access for all. However to restrict this access we will use ProxyInternetAccess class which will check user’s role and grant access based on their roles.

Class Diagram:

Protection Proxy Example

Protection Proxy Example

Code Example:

InternetAccess:

public interface InternetAccess {
	public void grantInternetAccess();
}

RealInternetAccess.java

public class RealInternetAccess implements InternetAccess {
	private String employeeName = null;

	public RealInternetAccess(String empName) {
		this.employeeName = empName;
	}

	@Override
	public void grantInternetAccess() {
		System.out.println("Internet Access granted for employee: "
				+ employeeName);
	}
}

ProxyInternetAccess.java

public class ProxyInternetAccess implements InternetAccess {
	private String empName = null;
	private RealInternetAccess objRealIA = null;

	public ProxyInternetAccess(String strEmployeeName) {
		this.empName = strEmployeeName;
	}

	@Override
	public void grantInternetAccess() {
		if (getRole(empName) > 5) {
			objRealIA = new RealInternetAccess(empName);
			objRealIA.grantInternetAccess();
		} else {
			System.out
					.println("No Internet access granted. " +
							"Your job level is below 5");
		}

	}

	public int getRole(String emplName) {
		// Check role database based on Name
		// return job level
		return 7;
	}

}

Client.java

public static void main(String[] args) {
		InternetAccess ia = new ProxyInternetAccess("Idiotechie");
		ia.grantInternetAccess();
	}

Benefits:

  • One of the advantages of Proxy pattern as you have seen in the above example is about security.
  • This pattern avoids duplication of objects which might be huge size and memory intensive. This in turn increases the performance of the application.
  • The remote proxy also ensures about security by installing the local code proxy (stub) in the client machine and then accessing the server with help of the remote code.

Drawbacks/Consequences:

This pattern introduces another layer of abstraction which sometimes may be an issue if the RealSubject code is accessed by some of the clients directly and some of them might access the Proxy classes. This might cause disparate behaviour.

Interesting points:

  • There are few differences between the related patterns. Like Adapter pattern gives a different interface to its subject, while Proxy patterns provides the same interface from the original object but the decorator provides an enhanced interface. Decorator pattern adds additional behaviour at runtime.
  • Proxy used in Java API:  java.rmi.*;

Please don’t forget to leave your comments. In case you like this article please share this articles for your friends through the social networking links.

Download Sample Code:

Download Sample Code

Filed in: Core Java, Design Pattern, Java, Random Tags: , , , , , , , , , , , ,

Get Updates

Share This Post

Related Posts

4 Responses to "Gang of Four – Proxy Design Pattern"

  1. Andrei Olaru says:

    Good article to describe the pattern! Well done!

    I have some questions: how would you implement a lazy-loading architecture through this pattern? Or would you not use it?

    • IdioTechie says:

      Hi Andrei,
      Thanks for visiting this article. Going by the definition of Lazy loading it is a design pattern to defer the initialization of an object until the point at which it is needed. If you refer to the Virtual Proxy example (ProxyImage.java : Line 14) we are trying to implement the Lazy loading already. The RealImage is not instantiated until it is first called. Hope this makes sense. Please let me know your thoughts.
      Cheers

  2. manoj says:

    Proxy Design Pattern in Java, lazy loading using Proxy Design Pattern

    What is Proxy Design Pattern

    1. Proxy design patten works on the principal of exposing an Java Instance through a proxy instead of actual object.

    2. Client would never know anything about actual object and through Proxy only relevant behavior of actual object will be exposed to client.

    3. Proxy Pattern can be used for applying security on actual Object. Service provider does not want actual class to be visible to any client Instead It would be shared as per Client contract agreement . Service provider may agree to share only a part of Service with it’s client and for that It may expose a different contract in the form of interface in java .

    4. This concept is very useful for lazily loading an instance . Data will be loaded only when it is actually required in an operation .

    Learn more about proxy design pattern here — Proxy Design Pattern

    http://efectivejava.blogspot.in/2013/09/proxy-design-pattern-in-java-lazy.html?utm_source=BP_recent

Leave a Reply

Submit Comment

© 2014 IdioTechie. All rights reserved.