设计模式第7篇:代理设计模式

一.代理设计模式要解决的问题

当需要设计控制访问权限功能时可以考虑代理设计模式。设想我们有一个执行系统命令的类,当我们自己用这个类时能够放心的使用,但当把这个类给客户端程序使用时就产生了一个严重问题,因为这个客户端程序可能通过这个类删除了系统文件或者更改某些系统配置,这个是我们不愿意看到的。

二.代理设计模式代码用例

下面通过控制访问权限代理类来进行代码说明

  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) && "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);
            }
        }
    }

}

  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());
        }
        
    }

}

三.代理设计模式通常使用场景

代理设计模式通常用来控制访问权限或者通过提供包装器来提高性能。

原文地址:https://www.cnblogs.com/quxiangxiangtiange/p/10235728.html