Tutorial

Proxy Design Pattern

Published on August 3, 2022
author

Pankaj

Proxy Design Pattern

Proxy Design pattern is one of the Structural design pattern and in my opinion one of the simplest pattern to understand.

Proxy Design Pattern

proxy design pattern Proxy design pattern intent according to GoF is: Provide a surrogate or placeholder for another object to control access to it. The definition itself is very clear and proxy design pattern is used when we want to provide controlled access of a functionality. Let’s say we have a class that can run some command on the system. Now if we are using it, its fine but if we want to give this program to a client application, it can have severe issues because client program can issue command to delete some system files or change some settings that you don’t want. Here a proxy class can be created to provide controlled access of the program.

Proxy Design Pattern - Main Class

Since we code Java in terms of interfaces, here is our interface and its implementation class. CommandExecutor.java

package com.journaldev.design.proxy;

public interface CommandExecutor {

	public void runCommand(String cmd) throws Exception;
}

CommandExecutorImpl.java

package com.journaldev.design.proxy;

import java.io.IOException;

public class CommandExecutorImpl implements CommandExecutor {

	@Override
	public void runCommand(String cmd) throws IOException {
                //some heavy implementation
		Runtime.getRuntime().exec(cmd);
		System.out.println("'" + cmd + "' command executed.");
	}

}

Proxy Design Pattern - Proxy Class

Now we want to provide only admin users to have full access of above class, if the user is not admin then only limited commands will be allowed. Here is our very simple proxy class implementation. CommandExecutorProxy.java

package com.journaldev.design.proxy;

public class CommandExecutorProxy implements CommandExecutor {

	private boolean isAdmin;
	private CommandExecutor executor;
	
	public CommandExecutorProxy(String user, String pwd){
		if("Pankaj".equals(user) && "J@urnalD$v".equals(pwd)) isAdmin=true;
		executor = new CommandExecutorImpl();
	}
	
	@Override
	public void runCommand(String cmd) throws Exception {
		if(isAdmin){
			executor.runCommand(cmd);
		}else{
			if(cmd.trim().startsWith("rm")){
				throw new Exception("rm command is not allowed for non-admin users.");
			}else{
				executor.runCommand(cmd);
			}
		}
	}

}

Proxy Design Pattern Client Program

ProxyPatternTest.java

package com.journaldev.design.test;

import com.journaldev.design.proxy.CommandExecutor;
import com.journaldev.design.proxy.CommandExecutorProxy;

public class ProxyPatternTest {

	public static void main(String[] args){
		CommandExecutor executor = new CommandExecutorProxy("Pankaj", "wrong_pwd");
		try {
			executor.runCommand("ls -ltr");
			executor.runCommand(" rm -rf abc.pdf");
		} catch (Exception e) {
			System.out.println("Exception Message::"+e.getMessage());
		}
		
	}

}

Output of above proxy design pattern example program is:

'ls -ltr' command executed.
Exception Message::rm command is not allowed for non-admin users.

Proxy design pattern common uses are to control access or to provide a wrapper implementation for better performance. Java RMI package uses proxy pattern. That’s all for proxy design pattern in java.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Pankaj

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
September 30, 2018

Just one thing wanted to check with you , should not it be good design if we do not expose proxy class to outer world and get it functionality done as kind of a filter before actually getting command fired. That is exactly kind of reference from your proxy class mentioned in serialization process blog. By doing this way outer world does not know internal structure whether there is any filter in place in middle.

- Amit

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    August 23, 2018

    In class CommandExecutorProxy, it looks like changing “private CommandExecutor executor;” to “private CommandExecutorImpl executor;” is more efficient. Why not use its implementation directly?

    - Ben qu

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      March 27, 2017

      Client application can directly create instance of CommandExecutorImpl class and invoke runCommand. How this can be avoided?

      - Yogesh

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        March 3, 2017

        Please explain all the 4 types of proxy pattern.

        - Vijay Raj R

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          July 9, 2016

          there is a chance of throwing NUllPointer Exception in the above program in case of the user is not an admin and the command he is issuing is not containing rm…

          - prasad

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            September 15, 2015

            awsem one …clearly understood the proxy pattern

            - aneesh

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              July 14, 2013

              Thanks, great tutorial. I will use it in future to provide restricted access.

              - Amit

                Try DigitalOcean for free

                Click below to sign up and get $200 of credit to try our products over 60 days!

                Sign up

                Join the Tech Talk
                Success! Thank you! Please check your email for further details.

                Please complete your information!

                Become a contributor for community

                Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                DigitalOcean Documentation

                Full documentation for every DigitalOcean product.

                Resources for startups and SMBs

                The Wave has everything you need to know about building a business, from raising funding to marketing your product.

                Get our newsletter

                Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

                New accounts only. By submitting your email you agree to our Privacy Policy

                The developer cloud

                Scale up as you grow — whether you're running one virtual machine or ten thousand.

                Get started for free

                Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

                *This promotional offer applies to new accounts only.