-
Notifications
You must be signed in to change notification settings - Fork 0
/
command.go
72 lines (59 loc) · 1.21 KB
/
command.go
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
package main
import "fmt"
/*
The Command pattern is a behavioral design pattern that transforms a request into a separate object that contains all the information related to the request.
This transformation allows you to parameterize methods,
delay request execution or enqueue them, and implement undoable operations based on different requests.
client initialization order:
1. create receiver
2. create command, relate it to receiver if necessary
3. create sender, and bonds it to specific command
*/
//sender
type button struct {
command command
}
func (b *button) press() {
b.command.execute()
}
//command
type command interface {
execute()
}
type onCommand struct {
tv device
}
func (c *onCommand) execute() {
c.tv.on()
}
type offCommand struct {
tv device
}
func (c *offCommand) execute() {
c.tv.off()
}
//receiver
type device interface {
on()
off()
}
type tv struct{}
func (t *tv) on() {
fmt.Printf("tv turn on\n")
}
func (t *tv) off() {
fmt.Printf("tv turn off\n")
}
func RunCommand() {
tv := &tv{}
onCommand := &onCommand{tv: tv}
offCommand := &offCommand{tv: tv}
onButton := &button{
command: onCommand,
}
offButton := &button{
command: offCommand,
}
onButton.press()
offButton.press()
}