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

2017-12-12  本文已影响5人  大厂offer

Proxy Design Pattern

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使用了代理模式。

上一篇 下一篇

猜你喜欢

热点阅读