1. 定义
将“请求”封装成对象,以便使用不同的请求、队列或者日志来参数化其他对象。该模式也支持可撤销的操作。
2. 角色
- Command:抽象命令类
- ConcreteCommand:具体命令类
- Invoker:调用者
- Receiver:接收者
- Client:客户类
3. 特点
- 优点:能实现命令的请求者和执行者的解耦,使系统易于扩展,支持宏命令,可将一组命令组合起来使用,可以方便地实现撤销操作。
- 缺点:因为每一个命令有一个相对的具体命令类,当命令过多时,影响命令模式的使用。
4. 示例:电灯开关
Light(命令的执行者):
public class Light {
public void on() {
System.out.println("light is on");
}
public void off() {
System.out.println("light is off");
}
}
LightCommand:
public abstract class LightCommand {
Light light;
public LightCommand(Light light) {
this.light = light;
}
public abstract void execute();
}
具体命令:
// LightOnCommand
public class LightOnCommand extends LightCommand {
public LightOnCommand(Light light) {
super(light);
}
@Override
public void execute() {
light.on();
}
}
// LightOffCommand
public class LightOffCommand extends LightCommand {
public LightOffCommand(Light light) {
super(light);
}
@Override
public void execute() {
light.off();
}
}
RemoteControl(命令的请求者):
public class RemoteControl {
LightCommand onCommand;
LightCommand offCommand;
public RemoteControl(LightCommand onCommand, LightCommand offCommand) {
this.onCommand = onCommand;
this.offCommand = offCommand;
}
public void onButton() {
onCommand.execute();
}
public void offButton() {
offCommand.execute();
}
}
测试类:
public class TestCommand {
public static void main(String[] args) {
Light light = new Light();
LightOnCommand onCommand = new LightOnCommand(light);
LightOffCommand offCommand = new LightOffCommand(light);
RemoteControl remoteControl = new RemoteControl(onCommand, offCommand);
remoteControl.onButton();
remoteControl.offButton();
}
}
// 输出
// light is on
// light is off
参考:
1. 《Head First 设计模式》
2. 《图说设计模式》 https://design-patterns.readthedocs.io/zh_CN/latest/behavioral_patterns/command.html