設計模式第7篇:代理設計模式
阿新 • • 發佈:2019-01-07
一.代理設計模式要解決的問題
當需要設計控制訪問許可權功能時可以考慮代理設計模式。設想我們有一個執行系統命令的類,當我們自己用這個類時能夠放心的使用,但當把這個類給客戶端程式使用時就產生了一個嚴重問題,因為這個客戶端程式可能通過這個類刪除了系統檔案或者更改某些系統配置,這個是我們不願意看到的。
二.代理設計模式程式碼用例
下面通過控制訪問許可權代理類來進行程式碼說明
1.系統命令執行介面類
interface CommandExecutor { public void runCommand(String cmd) throws Exception; }
2.系統命令執行介面類的實現
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."); } }
3.控制訪問許可權代理類
代理類通過將CommandExecutorImpl包裝來實現訪問許可權控制
class CommandExecutorProxy implements CommandExecutor { private boolean isAdmin; private CommandExecutor executor; public CommandExecutorProxy(String user, String pwd){ if("Pankaj".equals(user) && "[email protected]$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); } } } }
4.代理類測試
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()); } } }
三.代理設計模式通常使用場景
代理設計模式通常用來控制訪問許可權或者通過提供包裝器來提高效能。