01 定義
命令模式:將“請求”封裝成對象,以便使用不同的請求、隊列或者日志來參數化其他對象。命令模式也支持可撤銷的操作。
02 情景
通過電燈開關的按鈕來控制電燈的打開或者關閉。
03 類圖
CommandPattern.png
04 Class
// 燈:Receiver 接收者,真正執行命令的對象。
public class Light {
private String name;
public Light(String name) {
this.name = name;
}
// 開燈
public void on(){
System.out.println(String.format("The %s light is on", name));
}
// 關燈
public void off(){
System.out.println(String.format("The %s light is off", name));
}
}
// 定義命令的接口
public interface Command {
public void execute();
}
// 開燈命令: 命令接口實現對象,是“虛”的實現;通常會持有接收者(Light),并調用接收者的功能來完成命令要執行的操作。
public class LightOnCommand implements Command {
private Light light;
public LightOnCommand(Light light) {
this.light = light;
}
@Override
public void execute() {
light.on();
}
}
// 關燈命令: 命令接口實現對象,是“虛”的實現;通常會持有接收者(Light),并調用接收者的功能來完成命令要執行的操作。
public class LightOffCommand implements Command {
private Light light;
public LightOffCommand(Light light) {
this.light = light;
}
@Override
public void execute() {
light.off();
}
}
// Invoker:調用器
// 要求命令對象執行請求,通常會持有命令對象,可以持有很多的命令對象。
// 這個是客戶端真正觸發命令并要求命令執行相應操作的地方,也就是說相當于使用命令對象的入口。
public class RemoteControl {
private Command command;
public void setCommand(Command command){
this.command = command;
}
public void pressButton(){
command.execute();
}
}
05 測試
// Client:創建具體的命令對象,并且設置命令對象的接收者。
Light light = new Light("Living room");
LightOnCommand lightOnCommand = new LightOnCommand(light);
LightOffCommand lightOffCommand = new LightOffCommand(light);
RemoteControl remoteControl = new RemoteControl();
// 開燈
remoteControl.setCommand(lightOnCommand);
remoteControl.pressButton();
// 關燈
remoteControl.setCommand(lightOffCommand);
remoteControl.pressButton();
TestResult.png