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".
Advantages
Original object is protected.
Proxy patterns can be used as virtual proxy, protective proxy, remote proxy, and smart proxy.
Conceptual
figure
Subject :Subject is an interface implemented by the RealSubject and represents the services. The subject interface must be implemented by the proxy so that the proxy can be used in any location where the RealSubject is to be used.
Proxy : Proxy is used for maintaining a reference, which allows the Proxy to access the RealSubject.
Implements the same interface as of the RealSubject so that the Proxy can be a substitute for the RealSubject. It controls access to the RealSubject and is responsible for its creation & deletion.
Other responsibilities depend on the proxy type.
RealSubject : The real object represents the proxy.
Examples
Creating an interface Executor and importing the java.io.Ioexception package.
[java]
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.");
}
}[/java]
Creating a class CommandExecuterProxy which implements the interface Executor.
[java]
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);
}
}
}
}[/java]
Creating a ProxyPatternTest class.
[java]
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());
}
}
}[/java]
Output
Following is the result will be as follows.
[java]ls -ltr' command executed.
Exception Message::rm command is not allowed for non-admin users.[/java]
Summary
Key Points
Security for object can be achieved.
Proxy patterns are very simpler structural patterns.