Proxy Pattern

Provide a surrogate or placeholder for another object to control access to it. Use an extra level of indirection to support distributed, controlled, or intelligent access. Add a wrapper and delegation to protect the real component from undue complexity.


You need to support resource-hungry objects, and you do not want to instantiate such objects unless and until they are actually requested by the client.


Java Remote Method Invocation (RMI) – In java RMI an object on one machine (executing in one JVM) called a client can invoke methods on an object in another machine (another JVM) the second object is called a remote object. The proxy (also called a stub) resides on the client machine and the client invokes the proxy in as if it is invoking the object itself (remember that the proxy implements the same interface that RealSubject implements). The proxy itself will handle communication to the remote object, invoke the method on that remote object, and would return the result if any to the client. The proxy, in this case, is a Remote proxy.

Source Code (Java):

public interface IFolder {

	public void performOperations();
	public void downloadFile();
public class Folder implements IFolder {

	public void performOperations() {
		// access folder and perform various operations like copy files
		System.out.println("Performing operation on folder");

	public void downloadFile() {
		System.out.println("File is Downloading...");

public class FolderProxy implements IFolder {

	Folder folder;
	User user;

	public FolderProxy(User user) {
		this.user = user;

	public void performOperations() {

		if (user.getUserName().equalsIgnoreCase("toufiq")
				&& user.getPassword().equalsIgnoreCase("toufiq")) {
			folder = new Folder();
		} else {
			System.out.println("You don't have access to this folder");

	public void downloadFile() {
		// TODO Auto-generated method stub
		folder = new Folder();
public class User {

	String userName;
	String password;

	public User(String userName, String password) {
		this.userName = userName;
		this.password = password;

	public String getUserName() {
		return userName;

	public String getPassword() {
		return password;

public class MainClass {

	public static void main(String[] args) {

		User user = new User("toufiq", "toufiq");
		FolderProxy folderProxy = new FolderProxy(user);
		System.out.println("When userName and password are correct:");
		// if we give wrong userName and Password
		User userWrong = new User("abc", "abc");
		FolderProxy folderProxyWrong = new FolderProxy(userWrong);
		System.out.println("When userName and password are incorrect:");
		// Download File
		FolderProxy proxy = new FolderProxy(null);


Toufiq Mahmud

Leave a Reply

Your email address will not be published.