简介:命令模式将请求组成一个对象,进而对请求个性化封装后对客户端进行参数化。同时可以在请求处理过程中穿插其他处理,如日志、事务等。
代码实现及测试如下:
/**
* 命令接口
* @author dedu
*/
public interface Command {
void execute(String command);
}
class ConcreteCommand implements Command {
private Receiver receiver;
public ConcreteCommand(Receiver receiver) {
super();
this.receiver = receiver;
}
@Override
public void execute(String command) {
//可针对命令执行前后做处理
System.out.println("命令执行前:" + System.currentTimeMillis());
receiver.action(command);
System.out.println("命令执行后:" + System.currentTimeMillis());
}
}
/**
* 命令接收者
* @author dedu
*
*/
public class Receiver {
public void action(String command) {
System.out.println("命令接受者执行【" + command + "】命令!");
}
}
/**
* 命令发起者
* @author dedu
*
*/
public class Invoke {
private Command command;
public Invoke(Command command) {
super();
this.command = command;
}
public void call(String call) {
command.execute(call);
}
}
测试
public static void main(String[] args) {
Command command = new ConcreteCommand(new Receiver());
Invoke invoke = new Invoke(command);
invoke.call("学习");
}