1 /**
2 *命令模式:将“请求”封装成对象,以便使用不同的请求、队列或日志来参数化其他对象。
3 *命令模式也支持可撤销的操作。
4 */
5 /*
6 * 实现命令接口
7 */
8 public interface Command{
9 public void execute();
10 }
11
12 /*
13 * 一个具体打开电灯的命令
14 */
15 public class LightOnCommand implements Command{
16 Light light;
17
18 public LightOnCommand(Light light){
19 this.light = light;
20 }
21
22 public void execute(){
23 light.on();
24 }
25 }
26
27 /*
28 * 使用命令对象
29 */
30 public class SimpleRemoteControl{
31 Command slot;
32
33 public SimpleRemoteControl(){}
34
35 public void setCommand(Command command){
36 slot = command;
37 }
38
39 public void buttonWasPressed(){
40 slot.execute();
41 }
42 }
43
44 /*
45 * 简单测试
46 */
47 public class RemoteControlTest{
48 public static void main(String[] args){
49 SimpleRemoteControl remote = new SimpleRemoteControl();
50 Light light = new Light();
51 LightOnCommand lightOn = new LightOnCommand(light);
52
53 remote.setCommand(lightOn);
54 remote.buttonWasPressed();
55 }
56 }