-
Notifications
You must be signed in to change notification settings - Fork 0
/
fsm.go
66 lines (57 loc) · 1.16 KB
/
fsm.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
package fsm
type Transition struct {
From, To string
Event string
}
type Callback func(t *Transition, args ...interface{})
func OnEntry(to string, f Callback) Callback {
return func(t *Transition, args ...interface{}) {
if t.To == to {
f(t, args...)
}
}
}
func OnExit(from string, f Callback) Callback {
return func(t *Transition, args ...interface{}) {
if t.From == from {
f(t, args...)
}
}
}
func OnXXXEvent(event string, f Callback) Callback {
return func(t *Transition, args ...interface{}) {
if t.Event == event {
f(t, args...)
}
}
}
func OnTransEvent(from, to string, f Callback) Callback {
return func(t *Transition, args ...interface{}) {
if t.From == from && t.To == to {
f(t, args...)
}
}
}
type FSM struct {
Transitions []Transition
Callbacks []Callback
}
func (f FSM) Trigger(currentState string, event string) string {
var (
t Transition
exist bool
)
for _, tran := range f.Transitions {
if currentState == tran.From && tran.Event == event {
t, exist = tran, true
break
}
}
if !exist {
t = Transition{Event: event}
}
for _, callback := range f.Callbacks {
callback(&t)
}
return t.To
}