Proxy Design Pattern
-
代理模式的意图是根据Gof来的:提供一个代理或占位符控制访问的权限;
-
这个定义本身已经非常明确了,当我们要控制访问的权限就使用代理模式;
-
假如有一个类可以运行一些系统命令,现在我要将其作为客户端程序给用户使用,但是有个很严重的问题就是用户可以通过操作这个客户端删除一些系统文件或者更改设置,这是不允许的,于是代理模式应运而生;
Proxy Design Pattern – Main Class
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.");
}
}
Proxy Design Pattern – Proxy Class
现在我想提供一个拥有所有权限的admin,它可以访问上述的class,如果这个用户不是admin,那只有部分权限;
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);
}
}
}
}
Proxy Design Pattern Client Program
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.
Java RMI使用了代理模式。
网友评论