定义:将一个任务封装为一个拥有特定接口的对象,这样不同的请求(例如排队请求或者记录日志)对应的任务可以封装为拥有相同接口的不同对象,并且能够支持还原操作。
使用场景:拥有多个请求及其对应的任务,需要支持还原操作,例如排队请求或者记录日志请求。命令类自身执行请求而不是委托给接受者在实际应用场景中是很常见的。
类图:
代码样例:1)java线程的任务就相当于命令类
public class Light {
public Light() {
}
public void on() {
System.out.println("Light is on");
}
public void off() {
System.out.println("Light is off");
}
}
public class LightOffCommand implements Command {
Light light;
public LightOffCommand(Light light) {
this.light = light;
}
public void execute() {
light.off();
}
}
public class LightOnCommand implements Command {
Light light;
public LightOnCommand(Light light) {
this.light = light;
}
public void execute() {
light.on();
}
}
//
// This is the invoker
//
public class SimpleRemoteControl {
Command slot;
public SimpleRemoteControl() {}
public void setCommand(Command command) {
slot = command;
}
public void buttonWasPressed() {
slot.execute();
}
}
public class RemoteControlTest {
public static void main(String[] args) {
SimpleRemoteControl remote = new SimpleRemoteControl();
Light light = new Light();
GarageDoor garageDoor = new GarageDoor();
LightOnCommand lightOn = new LightOnCommand(light);
GarageDoorOpenCommand garageOpen =
new GarageDoorOpenCommand(garageDoor);
remote.setCommand(lightOn);
remote.buttonWasPressed();
remote.setCommand(garageOpen);
remote.buttonWasPressed();
}
}
优点:1)请求和执行动作完全解耦
缺点:
类似的设计模式:1)装饰者模式
配套的内功心法:1)