命令模式定义

将请求封装成对象,以便使用不同的请求,队列,或者日志来参数化其他对象。命令模式也可以支持可测销操作。

命令模式示意图

命令模式
命令模式

遥控器控制电灯打开的java代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// 一个普通的执行命令对象
public class Light {
public void on(){
log.info("light on...");
}
}
public interface Command {
// 命令接口只需要一个简单的执行方法
void execute();
}
//一个具体的命令实现,其中包含执行命令的对象light
public class LightOnCommand implements Command {
Light light;
public LightOnCommand(Light light) {
this.light=light;
}
// 当执行命令的时候,电灯打开
@Override
public void execute() {
this.light.on();
}
}
// 遥控控制类,包含一个命令插口引用,可以设置不同的命令
public class SimpleRemoteControl {
Command slot;
public SimpleRemoteControl(){}
public void setCommand(Command command){
this.slot=command;
}
// 当按钮按下的时候,调用插口实现的命令执行命令
public void buttonWasPressed(){
this.slot.execute();
}
}
// 代码测试
public class RemoteControlTest {
public static void main(String[] args) {
SimpleRemoteControl remote=new SimpleRemoteControl();
Light light=new Light();
// 创建一个打开电灯的命令,将电灯传进去
LightOnCommand lightOnCommand=new LightOnCommand(light);
// 遥控器设置一个命令
remote.setCommand(lightOnCommand);
// 按下按钮执行命令
remote.buttonWasPressed();
}
}