-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStateMachine.go
65 lines (49 loc) · 1.24 KB
/
StateMachine.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
package wei2
import "errors"
type StateMachine struct {
transitionMap map[string]map[int]*Transition;
}
type Transition struct {
preType string;
currentType string;
handle func(event Event);
}
type Event struct {
EventStatus int;
}
func NewStateMachine() (*StateMachine) {
m := new(StateMachine);
m.transitionMap=make(map[string]map[int]*Transition);
return m;
}
func (m *StateMachine) Add(preState string, curState string, handle func(event Event), eventStatus int) (err error){
if &handle == nil{
err = errors.New("handle is null")
return err;
}
transitionMap := m.transitionMap[preState]
if transitionMap == nil {
transitionMap = make(map[int]*Transition)
m.transitionMap[preState]=transitionMap
}
transition := new(Transition)
transition.currentType=curState
transition.preType=preState
transition.handle=handle
transitionMap[eventStatus]=transition
return
}
func (m*StateMachine)Transition(preType string, event Event)(err error) {
transitionMap := m.transitionMap[preType]
if transitionMap==nil {
err=errors.New("preType is not exist.")
return
}
transition := transitionMap[event.EventStatus]
if transition == nil{
err=errors.New("preType is not exist.")
return
}
transition.handle(event)
return
}