当我们要提供的功能控制的访问。比方说,我们有一个可以在系统上运行一些命令的类。现在,如果我们在使用它,没有任何问题,但如果我们想要这个程序给客户端应用程序,它可以有严重的问题,因为客户端程序可以发出命令来删除一些系统文件或更改了某些设置,这些操作并不是你想要的。这个时候创建代理类可以限制程序访问某些命令。
Java是以接口为设计原则,这里是我们的接口和实现类。
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."); } }
代理类:
现在我们想只有管理员用户才有完整的访问功能,若不是管理员用户则限制部分命令使用,下面是一个简单代理实现,
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); } } } }
代理测试类:
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()); } } }
输出结果:
'ls -ltr'
command
executed.
Exception Message::
rm
command
is not allowed
for
non-admin
users
.
代理模式常见的用途是控制访问或提供的包装实现更好的性能。
原文链接:http://www.journaldev.com/1572/proxy-design-pattern