Skip to content

Commit f49bf79

Browse files
committed
add command design pattern
1 parent 12211c0 commit f49bf79

File tree

2 files changed

+68
-0
lines changed

2 files changed

+68
-0
lines changed

command/command.go

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
package command
2+
3+
import "fmt"
4+
5+
type ICommand interface {
6+
Excute()
7+
Cancel()
8+
}
9+
10+
type Revicer struct {
11+
}
12+
13+
func (r *Revicer) Do() {
14+
fmt.Println("revicer do something")
15+
}
16+
17+
func (r *Revicer) UnDo() {
18+
fmt.Println("revicer undo something")
19+
}
20+
21+
type CreateCommand struct {
22+
revicer *Revicer
23+
}
24+
25+
func (c *CreateCommand) SerRevicer(s *Revicer) {
26+
c.revicer = s
27+
}
28+
29+
func (c *CreateCommand) Excute() {
30+
c.revicer.Do()
31+
}
32+
33+
func (c *CreateCommand) Cancel() {
34+
c.revicer.UnDo()
35+
}
36+
37+
type Invoker struct {
38+
command ICommand
39+
}
40+
41+
func (i *Invoker) SetCmd(c ICommand) {
42+
i.command = c
43+
}
44+
45+
func (i *Invoker) ExcuteCmd() {
46+
i.command.Excute()
47+
}
48+
49+
func (i *Invoker) CancelCmd() {
50+
i.command.Cancel()
51+
}

command/command_test.go

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package command
2+
3+
import "testing"
4+
5+
func TestCommand(t *testing.T) {
6+
r := new(Revicer)
7+
c := new(CreateCommand)
8+
c.SerRevicer(r)
9+
invoker := Invoker{}
10+
invoker.SetCmd(c)
11+
12+
invoker.ExcuteCmd()
13+
invoker.CancelCmd()
14+
//out
15+
//revicer do something
16+
//revicer undo something
17+
}

0 commit comments

Comments
 (0)