命令模式
命令模式把一个请求或者操作封装到一个对象中。命令模式允许系统使用不同的请求把客户端参数化,对请求排队或者记录请求日志,可以提供命令的撤销和恢复功能
UML
Java
- 定义Command接口:
public interface Command { void exec(); }
- 实现命令执行者Receiver:
public class Receiver { public void action() { System.out.println("command received!"); } }
- 实现真正的命令,转发给执行者执行
public class MyCommand implements Command { private final Receiver receiver; public MyCommand(final Receiver receiver) { this.receiver = receiver; } @Override public void exec() { receiver.action(); } }
- 实现命令发起者Invoker:
public class Invoker { private final Command command; public Invoker(final Command command) { this.command = command; } public void action() { command.exec(); } }
- 测试代码,命令者发起命令,命令转给执行者,执行者执行命令:
public class CommandTest { public static void main(String[] args) { Receiver receiver = new Receiver(); Command cmd = new MyCommand(receiver); Invoker invoker = new Invoker(cmd); invoker.action(); } }
- 测试结果:
command received!
Scheme
- 传入command函数作为参数:
(define (invoke command op) (command op))
- 测试:
(invoke (lambda (op) (begin (display "command received") (newline) "command finished")) '()) ;; => command received ;; command finished