File tree 3 files changed +105
-0
lines changed
3 files changed +105
-0
lines changed Original file line number Diff line number Diff line change
1
+ # 命令模式
2
+
3
+ 命令模式本质是把某个对象的方法调用封装到对象中,方便传递、存储、调用。
4
+
5
+ 示例中把主板单中的启动(start)方法和重启(reboot)方法封装为命令对象,再传递到主机(box)对象中。于两个按钮进行绑定:
6
+
7
+ * 第一个机箱(box1)设置按钮1(buttion1) 为开机按钮2(buttion2)为重启。
8
+ * 第二个机箱(box1)设置按钮2(buttion2) 为开机按钮1(buttion1)为重启。
9
+
10
+ 从而得到配置灵活性。
11
+
12
+
13
+ 除了配置灵活外,使用命令模式还可以用作:
14
+
15
+ * 批处理
16
+ * 任务队列
17
+ * undo, redo
18
+
19
+ 等把具体命令封装到对象中使用的场合
20
+
Original file line number Diff line number Diff line change
1
+ package command
2
+
3
+ import "fmt"
4
+
5
+ type Command interface {
6
+ Execute ()
7
+ }
8
+
9
+ type StartCommand struct {
10
+ mb * MotherBoard
11
+ }
12
+
13
+ func NewStartCommand (mb * MotherBoard ) * StartCommand {
14
+ return & StartCommand {
15
+ mb : mb ,
16
+ }
17
+ }
18
+
19
+ func (c * StartCommand ) Execute () {
20
+ c .mb .Start ()
21
+ }
22
+
23
+ type RebootCommand struct {
24
+ mb * MotherBoard
25
+ }
26
+
27
+ func NewRebootCommand (mb * MotherBoard ) * RebootCommand {
28
+ return & RebootCommand {
29
+ mb : mb ,
30
+ }
31
+ }
32
+
33
+ func (c * RebootCommand ) Execute () {
34
+ c .mb .Reboot ()
35
+ }
36
+
37
+ type MotherBoard struct {}
38
+
39
+ func (* MotherBoard ) Start () {
40
+ fmt .Print ("system starting\n " )
41
+ }
42
+
43
+ func (* MotherBoard ) Reboot () {
44
+ fmt .Print ("system rebooting\n " )
45
+ }
46
+
47
+ type Box struct {
48
+ buttion1 Command
49
+ buttion2 Command
50
+ }
51
+
52
+ func NewBox (buttion1 , buttion2 Command ) * Box {
53
+ return & Box {
54
+ buttion1 : buttion1 ,
55
+ buttion2 : buttion2 ,
56
+ }
57
+ }
58
+
59
+ func (b * Box ) PressButtion1 () {
60
+ b .buttion1 .Execute ()
61
+ }
62
+
63
+ func (b * Box ) PressButtion2 () {
64
+ b .buttion2 .Execute ()
65
+ }
Original file line number Diff line number Diff line change
1
+ package command
2
+
3
+ func ExampleCommand () {
4
+ mb := & MotherBoard {}
5
+ startCommand := NewStartCommand (mb )
6
+ rebootCommand := NewRebootCommand (mb )
7
+
8
+ box1 := NewBox (startCommand , rebootCommand )
9
+ box1 .PressButtion1 ()
10
+ box1 .PressButtion2 ()
11
+
12
+ box2 := NewBox (rebootCommand , startCommand )
13
+ box2 .PressButtion1 ()
14
+ box2 .PressButtion2 ()
15
+ // Output:
16
+ // system starting
17
+ // system rebooting
18
+ // system rebooting
19
+ // system starting
20
+ }
You can’t perform that action at this time.
0 commit comments