As the name suggests, in this pattern we create a proxy object for an actual object and use the proxy object instead of actual object, which intern internally invokes actual objects functionality. Here, proxy object mimics the actual object.

GoF Definition: Provide a surrogate or placeholder for another object to control access to it.

Proxy pattern can be used to create a wrapper for actual objects or to provide restricted/controlled access to the real object for outside clients. Using the proxy pattern also limits the unwanted object creation, as it is handled by the proxy object.

This design pattern comes under Structural design pattern.

Proxy Design Pattern Example in Java

In the following section we will see how to implement proxy design pattern in Java. We will create a Subject interface, a real object class which implements the Subject interface and a proxy object class, which wraps the real object, controls creation of real object, invokes real objects functionality internally when it is used by the outside clients. Finally, we access the real object through proxy object from an example demo class by creating an instance of proxy object.

Create an interface called Subject as shown below. This interface will have the required methods to be implemented by the real and proxy objects.

Subject.java

package com.asb.proxy;

public interface Subject {	

	public void callMethod();
}

Create an implementation class for real object and another implementation class for proxy object as shown below. Here, RealSubject class implements Subject interface and provides callMethod() method.

RealSubject.java

package com.asb.proxy;

public class RealSubject implements Subject {

	@Override
	public void callMethod() {
		
		System.out.println("Calling RealSubject method()");
	}
}

Create a proxy class ProxySubject as shown below. We use this proxy object to invoke methods of RealSubject class. This class acts as a proxy for the actual RealSubject class. Notice that proxy object controls the creation of RealSubject class object.

ProxySubject.java

package com.asb.proxy;

public class ProxySubject implements Subject {

	private RealSubject realSubject;
	
	@Override
	public void callMethod() {
		
		System.out.println("Calling ProxySubject method!!");
		
		if(null == realSubject){
			realSubject = new RealSubject();
		}
		realSubject.callMethod();
	}
}

Finally, create a demo class with main method. In this class, inside main method we are creating a proxy object instance and invoking the callMethod() method.

ProxyPatternDemo.java

package com.asb.proxy;

public class ProxyPatternDemo {

	public static void main(String args[]) {
		
		System.out.println("Proxy Pattern Demo...");
		//Create proxy object
		ProxySubject subject = new ProxySubject();
		subject.callMethod();
	}
}

Output

You may also interested in :