代理设计模式是结构设计模式之一,在我看来是最简单的模式之一。
代理设计模式
Proxy design pattern intent according to GoF is: Provide a surrogate or placeholder for another object to control access to it. The definition itself is very clear and proxy design pattern is used when we want to provide controlled access of a functionality. Let's say we have a class that can run some command on the system. Now if we are using it, its fine but if we want to give this program to a client application, it can have severe issues because client program can issue command to delete some system files or change some settings that you don't want. Here a proxy class can be created to provide controlled access of the program.
代理设计模式 - 主类
由于我们在界面上编码Java,所以这里是我们的界面和其实现类。
1package com.journaldev.design.proxy;
2
3public interface CommandExecutor {
4
5 public void runCommand(String cmd) throws Exception;
6}
首页 > 管理员 > Java
1package com.journaldev.design.proxy;
2
3import java.io.IOException;
4
5public class CommandExecutorImpl implements CommandExecutor {
6
7 @Override
8 public void runCommand(String cmd) throws IOException {
9 //some heavy implementation
10 Runtime.getRuntime().exec(cmd);
11 System.out.println("'" + cmd + "' command executed.");
12 }
13
14}
代理设计模式 - 代理类
现在我们只想提供管理员用户才能完全访问上面的类,如果用户不是管理员,那么只有有限的命令才会被允许。
1package com.journaldev.design.proxy;
2
3public class CommandExecutorProxy implements CommandExecutor {
4
5 private boolean isAdmin;
6 private CommandExecutor executor;
7
8 public CommandExecutorProxy(String user, String pwd){
9 if("Pankaj".equals(user) && "J@urnalD$v".equals(pwd)) isAdmin=true;
10 executor = new CommandExecutorImpl();
11 }
12
13 @Override
14 public void runCommand(String cmd) throws Exception {
15 if(isAdmin){
16 executor.runCommand(cmd);
17 }else{
18 if(cmd.trim().startsWith("rm")){
19 throw new Exception("rm command is not allowed for non-admin users.");
20 }else{
21 executor.runCommand(cmd);
22 }
23 }
24 }
25
26}
代理设计模式客户端程序
「ProxyPatternTest.java」
1package com.journaldev.design.test;
2
3import com.journaldev.design.proxy.CommandExecutor;
4import com.journaldev.design.proxy.CommandExecutorProxy;
5
6public class ProxyPatternTest {
7
8 public static void main(String[] args){
9 CommandExecutor executor = new CommandExecutorProxy("Pankaj", "wrong_pwd");
10 try {
11 executor.runCommand("ls -ltr");
12 executor.runCommand(" rm -rf abc.pdf");
13 } catch (Exception e) {
14 System.out.println("Exception Message::"+e.getMessage());
15 }
16
17 }
18
19}
上面的 proxy 设计模式示例程序的输出是:
1'ls -ltr' command executed.
2Exception Message::rm command is not allowed for non-admin users.
代理设计模式的常见用途是控制访问或提供包装实现,以获得更好的性能。Java RMI包使用代理模式。