命令模式
一、定义
将请求封装为一个对象,从而使你可以用不同的请求参数化客户端,对请求排队或记录请求日志,而且支持操作的撤销和复原。
二、类图表示
三、实现
1、Receiver
package pattern.behavioral.command;
public class Receiver {
public void action(){
System.out.println("receiver action...");
}
public void doSomething(){
System.out.println("receiver do something...");
}
}
2、Command
package pattern.behavioral.command;
public abstract class Command {
protected Receiver receiver;
public Command(Receiver receiver) {
this.receiver = receiver;
}
public abstract void execute();
}
package pattern.behavioral.command;
public class ConcreteCommandA extends Command {
public ConcreteCommandA(Receiver receiver) {
super(receiver);
}
@Override
public void execute() {
receiver.action();
}
}
package pattern.behavioral.command;
public class ConcreteCommandB extends Command {
public ConcreteCommandB(Receiver receiver) {
super(receiver);
}
@Override
public void execute() {
receiver.doSomething();
}
}
3、Invoker
package pattern.behavioral.command;
public class Invoker {
private Command command;
public Invoker(Command command) {
this.command = command;
}
public void setCommand(Command command) {
this.command = command;
}
public void executeCommand(){
command.execute();
}
}
四、使用
package pattern.behavioral.command;
public class Client {
public static void main(String[] args) {
Receiver receiver = new Receiver();
Invoker invoker = new Invoker(new ConcreteCommandA(receiver));
invoker.executeCommand();
System.out.println();
invoker.setCommand(new ConcreteCommandB(receiver));
invoker.executeCommand();
}
}
- 程序输出:
receiver action...
receiver do something...
五、适用场合
-
抽象出待执行的动作以参数化某对象,类似于面象过程语言中的回调机制
-
在不同的时刻指定、排列和执行请求(一个Command对象可以有一个与初始请求无关的生存期)
-
支持撤销操作(Command的execute操作可以在具体操作前将状态存储起来,在撤销时可使用这个状态做恢复)
-
记录修改日志,当系统崩溃时,可通过Command中的操作记录重做这些修改
-
支持事务系统:一个事务封装了对数据的一组变动,Command模式提供了对事务进行建模的方法。Command有一个公共的接口,因此可以使用同一种方式调用所有的事务,而且该模式也易于添加新事务以扩展系统