设计模式之--命令模式
1.命令模式的定义
Encapsulate a request as an object,there by letting you parameterize clients with different requests,queue or log requests,and support undoable operations.
将请求封装成一个对象,从而让你使用不同的请求把客户端参数化,对请求排队或者记录请求日志,可提供命令的撤销和恢复功能。
2.命令模式的通用类图
命令模式通用类图如下:
在类图中的三个角色描述如下:
Receiver:
命令接受者,执行命令的对象
Command:
具体命令的包装类,所有命令都在此类中声明
Invoker:
接收到命令,并且执行命令,充当管理者的角色
相关代码如下:
Receiver:
public abstract class Receiver {
/**
* 命令的具体执行者
*/
public abstract void doSomething();
}
ConcreteReceiver:
public class ConcreteReceiver extends Receiver {
@Override
public void doSomething() {
System.out.println("Do something.");
}
}
Command:
public abstract class Command {
/**
* 执行命令
*/
public abstract void executor();
}
ConcreteCommand:
public class ConcreteCommand extends Command {
private Receiver receiver;
ConcreteCommand(Receiver receiver) {
this.receiver = receiver;
}
@Override
public void executor() {
this.receiver.doSomething();
}
}
Invoker:
public class Invoker {
private Command command;
public Invoker() {
}
public void action(){
this.command.executor();
}
public void setCommand(Command command) {
this.command = command;
}
}
Client:
public class Client {
public static void main(String[] args) throws Exception {
Invoker invoker = new Invoker();
Receiver receiver = new ConcreteReceiver();
Command command = new ConcreteCommand(receiver);
invoker.setCommand(command);
invoker.action();
}
}
3.命令模式的优缺点
优点:
调用者和接受者之间的解藕
Command可以有多个子类,可扩展性比较高
缺点:
当命令比较多的时候,会出现Command有N个子类的情况
4.命令模式的使用场景
GUI事件监听、Spring的事件监听、Redis的pub/sub等