當咱們要提供的功能控制的訪問。比方說,咱們有一個能夠在系統上運行一些命令的類。如今,若是咱們在使用它,沒有任何問題,但若是咱們想要這個程序給客戶端應用程序,它能夠有嚴重的問題,由於客戶端程序能夠發出命令來刪除一些系統文件或更改了某些設置,這些操做並非你想要的。這個時候建立代理類能夠限制程序訪問某些命令。java
Java是以接口爲設計原則,這裏是咱們的接口和實現類。bash
CommandExecutor.javaide
package com.journaldev.design.proxy; public interface CommandExecutor { public void runCommand(String cmd) throws Exception; }
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.javaspa
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
代理