代理模式是结构型模式中的一种,在GOF中有如下介绍

为另外一个对象提供代理,以便可以访问该对象

当我们需要实现控制访问的功能,就可以使用该模式

就拿linux系统命令而言,并不是所有的命令普通用户都可以执行的,这里linux系统的用户的权限管理模块就是一种代理,当用户想要执行命令时,最终都会代理到该模块,然后执行相应的命令

我们就简单的以执行命令为例子来实现代理模式

首先从接口开始编写代码

接口类

CommandExecutor.java

1
2
3
4
5
package com.walterlife.dp.ProxyDP;

public interface CommandExecuter {
public void runCommand(String cmd) throws Exception;
}

接口实现类

CommandExecutorImp.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package com.walterlife.dp.ProxyDP;

import java.io.IOException;

import org.apache.log4j.Logger;

public class CommandExecuterImpl implements CommandExecuter {

private static Logger logger = Logger.getLogger(CommandExecuter.class);

public void runCommand(String cmd) throws IOException {
Runtime.getRuntime().exec(cmd);
logger.info("CommandExecuter run cmd: " + cmd);
}
}

代理类

在这里我们假设admin用户就是root用户,用户权限执行所有命令,其中rm 命令 非root用户不能执行

CommandExecutorProxy.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package com.walterlife.dp.ProxyDP;

public class CommandExecuterProxy {
private boolean isAdmin = false;
private CommandExecuter commondExecuter;

public CommandExecuterProxy(String user, String pwd) {
if("admin".equals(user.toLowerCase())
&& "admin".equals(pwd)) {
isAdmin = true;
} else {
isAdmin = false;
}
commondExecuter = new CommandExecuterImpl();
}

public void runCommand(String cmd) throws Exception {
if(isAdmin) {
commondExecuter.runCommand(cmd);
} else {
if(cmd.trim().startsWith("rm")) {
throw new Exception("CommandExecuterProxy runCommand: cmd " + cmd + " not permit for user except admin!!!");
} else {
commondExecuter.runCommand(cmd);
}
}
}
}

测试代码

1
2
3
4
5
6
7
8
9
public static void testProxy() {
CommandExecuterProxy commondExecuterProxy = new CommandExecuterProxy("nadmin", "admin");
try {
commondExecuterProxy.runCommand("ls -lrt");
commondExecuterProxy.runCommand("rm tt");
} catch(Exception e) {
logger.error("Exception message: " + e.getMessage());
}
}

测试输出

1
2
2015-09-06 03:48:33 INFO  com.walterlife.dp.ProxyDP.CommandExecuterImpl runCommand:13 -> CommandExecuter run cmd: ls -lrt
2015-09-06 03:48:33 ERROR com.walterlife.dp.App testProxy:48 -> Exception message: CommandExecuterProxy runCommand: cmd rm tt not permit for user except admin!!!

留言