-
Notifications
You must be signed in to change notification settings - Fork 16
/
statemachine.go
36 lines (30 loc) · 1.04 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
package statemachine
// An implementation of a finite state machine in Go,
// inspired by David Mertz's article "Charming Python: Using state machines"
// (http://www.ibm.com/developerworks/library/l-python-state/index.html)
type Handler func(interface{}) (string, interface{})
type Machine struct {
Handlers map[string]Handler
StartState string
EndStates map[string]bool
}
func (machine *Machine) AddState(handlerName string, handlerFn Handler) {
machine.Handlers[handlerName] = handlerFn
}
func (machine *Machine) AddEndState(endState string) {
machine.EndStates[endState] = true
}
func (machine *Machine) Execute(cargo interface{}) {
if handler, present := machine.Handlers[machine.StartState]; present {
for {
nextState, nextCargo := handler(cargo)
_, finished := machine.EndStates[nextState]
if finished {
break
} else {
handler, present = machine.Handlers[nextState]
cargo = nextCargo
}
}
}
}