• 设计模式第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());
            }
            
        }
    
    }

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

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

  • 相关阅读:
    试用solace 消息平台
    mqtt5 share subscription 简单说明
    文件批量重命名神器:Bulk Rename Utility
    Elasticsearch入门,这一篇就够了
    burp suite使用(一) --- 抓包,截包,改包
    BurpSuite安装和配置
    ORA-01779: 无法修改与非键值保存表对应的列”中涉及的概念和解决方法
    一个非常有用的函数——COALESCE
    ORA-01779: cannot modify a column which maps to a non-key-preserved table
    Oracle批量、大量Update方法总结
  • 原文地址:https://www.cnblogs.com/quxiangxiangtiange/p/10235728.html
Copyright © 2020-2023  润新知