文章目录
  1. 命令模式

命令模式

  • 将一个请求封装为一个对象,从而使你可用不同的请求对客户进行参数化;对请求排队或记录请求日志,以及支持可撤销的操作。
    Command
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
public class Light {
public void on() {
System.out.println("灯点亮");
}
public void off() {
System.out.println("灯熄灭");
}
}
public class TV {
public void on() {
System.out.println("TV打开");
}
public void off() {
System.out.println("TV关闭");
}
}
public interface Command {
void execute();
}
public class LightOnCommand implements Command{
private Light light;
public LightOnCommand(Light light) {
this.light = light;
}
@Override public void execute() {
light.on();
}
}
public class LightOffCommand implements Command {
private Light light;
public LightOffCommand(Light light) {
this.light = light;
}
@Override public void execute() {
light.off();
}
}
public class TVOnCommand implements Command{
private TV tv;
public TVOnCommand(TV tv) {
this.tv = tv;
}
@Override public void execute() {
tv.on();
}
}
public class TVOffCommand implements Command{
private TV tv;
public TVOffCommand(TV tv) {
this.tv = tv;
}
@Override public void execute() {
tv.off();
}
}
public class SwitchInvoker {
private Command onCommand;
private Command offCommand;
public void setOnCommand(Command onCommand) {
this.onCommand = onCommand;
}
public void setOffCommand(Command offCommand) {
this.offCommand = offCommand;
}
public void on(){
onCommand.execute();
}
public void off(){
offCommand.execute();
}
}
public class App {
public static void main(String[] args) {
//购买电器
Light light=new Light();
TV tv=new TV();
//配置电器
Command lightOnCommand=new LightOnCommand(light);
Command lightOffCommand=new LightOffCommand(light);
Command tvOnCommand=new TVOnCommand(tv);
Command tvOffCommand=new TVOffCommand(tv);
//安装开关并连接电器
SwitchInvoker commonSwitch=new SwitchInvoker();
//这一步相当于用电线将电器与开关相连接
//开关并不知道要开关谁,
commonSwitch.setOnCommand(lightOnCommand);
commonSwitch.setOffCommand(lightOffCommand);
//操作电器
commonSwitch.on();
commonSwitch.off();
//装修更改线路
//这里表达"使你可用不同的请求对客户参数化(将客户端参数化)"
commonSwitch.setOnCommand(tvOnCommand);
commonSwitch.setOffCommand(tvOffCommand);
//操作电器
commonSwitch.on();
commonSwitch.off();
}
}
文章目录
  1. 命令模式