Design Patterns - SPLessons

Proxy Pattern

Chapter 16

SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Proxy Pattern

Proxy Pattern

shape Description

Proxy pattern is a structural pattern that is mainly used to control the access of a class. The functionality of the class can be represented by another class. If one object represents another object, then it is known as “Proxy”. Proxy patterns are also known as Surrogate or Placeholder”.

shape Advantages

  • Original object is protected.
  • Proxy patterns can be used as virtual proxy, protective proxy, remote proxy, and smart proxy.

shape Conceptual
figure

shape Examples

Creating an interface Executor and importing the java.io.Ioexception package.

public interface Executor
{
public void runCommand(String cmd) throws Exception;
}
public class CommandExecutorImpl implements Executor
{
public void runCommand(String cmd) throws IOException
{
Runtime.getRuntime().exec(cmd);
System.out.println("'" + cmd + "' command executed.");
}
}

Creating a class CommandExecuterProxy which implements the interface Executor.

public class CommandExecutorProxy implements Executor
{
private boolean isAdmin;
private CommandExecutor executor;
public CommandExecutorProxy(String user, String pwd)
{
if("Punk".equals(user) && "Enrique".equals(pwd)) isAdmin=true;
executor = new CommandExecutorImpl();
}
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);
}
}
}
}

Creating a ProxyPatternTest class.

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

shape Output

Following is the result will be as follows.

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

Summary

shape Key Points

  • Security for object can be achieved.
  • Proxy patterns are very simpler structural patterns.