forked from AlexanderGrom/go-patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
command.go
67 lines (55 loc) · 1.3 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
// Package command is an example of the Command Pattern.
package command
// Command provides a command interface.
type Command interface {
Execute() string
}
// ToggleOnCommand implements the Command interface.
type ToggleOnCommand struct {
receiver *Receiver
}
// Execute command.
func (c *ToggleOnCommand) Execute() string {
return c.receiver.ToggleOn()
}
// ToggleOffCommand implements the Command interface.
type ToggleOffCommand struct {
receiver *Receiver
}
// Execute command.
func (c *ToggleOffCommand) Execute() string {
return c.receiver.ToggleOff()
}
// Receiver implementation.
type Receiver struct {
}
// ToggleOn implementation.
func (r *Receiver) ToggleOn() string {
return "Toggle On"
}
// ToggleOff implementation.
func (r *Receiver) ToggleOff() string {
return "Toggle Off"
}
// Invoker implementation.
type Invoker struct {
commands []Command
}
// StoreCommand adds command.
func (i *Invoker) StoreCommand(command Command) {
i.commands = append(i.commands, command)
}
// UnStoreCommand removes command.
func (i *Invoker) UnStoreCommand() {
if len(i.commands) != 0 {
i.commands = i.commands[:len(i.commands)-1]
}
}
// Execute all commands.
func (i *Invoker) Execute() string {
var result string
for _, command := range i.commands {
result += command.Execute() + "\n"
}
return result
}