一, 定义
命令模式 (command): 将一个请求封装为一个对象, 从而使你可用不同的请求对客户进行参数化; 对请求排队或记录请求日志, 以及支持可撤销的操作.
二, 示例代码
- public abstract class Command {
- protected Receiver receiver;
- public Command(Receiver receiver) {
- this.receiver = receiver;
- }
- abstract public void Execute();
- }
- public class ConcreteCommand extends Command {
- public ConcreteCommand(Receiver receiver) {
- super(receiver);
- }
- @Override
- public void Execute() {
- receiver.action();
- }
- }
- public class Invoker {
- private Command command;
- public void setCommand(Command command) {
- this.command = command;
- }
- public void executeCommand(){
- command.Execute();
- }
- }
- public class Receiver {
- public void action() {
- System.out.println("执行请求");
- }
- }
- public class Client {
- public static void main(String[] args) {
- Receiver receiver = new Receiver();
- Command command = new ConcreteCommand(receiver);
- Invoker invoker = new Invoker();
- invoker.setCommand(command);
- invoker.executeCommand();
- }
- }
三, 作用
1. 它能较容易地设计一个命令队列;
2. 在需要的情况下, 可以较容易地将命令记录日志;
3. 允许接收请求的一方决定是否要否决请求;
4. 容易地实现对请求的撤销和重做;
来源: http://www.bubuko.com/infodetail-3395561.html