代理设计模式
时间:2020-02-23 14:37:24 来源:igfitidea点击:
代理设计模式是结构设计模式之一,在我看来,这是最容易理解的模式之一。
代理设计模式
根据GoF的代理设计模式意图是:
为另一个对象提供代理或者占位符,以控制对其的访问。
定义本身非常清晰,当我们要提供功能的受控访问时,将使用代理设计模式。
假设我们有一个可以在系统上运行某些命令的类。
现在,如果我们正在使用它,就可以了,但是如果我们想将此程序提供给客户端应用程序,则它可能会出现严重问题,因为客户端程序可以发出命令来删除某些系统文件或者更改某些不需要的设置。
在这里可以创建代理类以提供程序的受控访问。
代理设计模式–主类
由于我们使用接口对Java进行编码,因此这里是我们的接口及其实现类。
CommandExecutor.java
package com.theitroad.design.proxy;
public interface CommandExecutor {
public void runCommand(String cmd) throws Exception;
}
CommandExecutorImpl.java
package com.theitroad.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.");
}
}
代理设计模式–代理类
现在,我们只想提供具有上述类的完全访问权限的admin用户,如果该用户不是admin,则将只允许使用有限的命令。
这是我们非常简单的代理类实现。
CommandExecutorProxy.java
package com.theitroad.design.proxy;
public class CommandExecutorProxy implements CommandExecutor {
private boolean isAdmin;
private CommandExecutor executor;
public CommandExecutorProxy(String user, String pwd){
if("hyman".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.theitroad.design.test;
import com.theitroad.design.proxy.CommandExecutor;
import com.theitroad.design.proxy.CommandExecutorProxy;
public class ProxyPatternTest {
public static void main(String[] args){
CommandExecutor executor = new CommandExecutorProxy("hyman", "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.
代理设计模式的常见用途是控制访问或者提供包装器实现以提高性能。

