-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathmain.go
59 lines (46 loc) · 1.72 KB
/
main.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
package main
import (
"fmt"
"github.com/Gurpartap/statemachine-go"
)
type Turnstile struct {
// Embed the state machine into our turnstile.
statemachine.Machine
// DisplayMsg stores the text that is displayed to the user.
// Contains either "Pay" or "Go".
DisplayMsg string
}
func main() {
turnstile := &Turnstile{}
turnstile.DisplayMsg = "Pay"
// Here we're embedding `statemachine.Machine` into our Turnstile struct.
// Embedding, although not necessary, is a suitable way to apply the
// state machine behaviour to the struct itself. Turnstile's DisplayMsg
// variable stores the text that is displayed to the user, and may store
// either "Pay" or "Go", depending on the state.
//
// Now let's set our state machine's definitions utilizing `MachineBuilder`:
turnstile.Machine = statemachine.BuildNewMachine(func(m statemachine.MachineBuilder) {
// States may be pre-defined here.
m.States("locked", "unlocked")
// Initial State is required to start the state machine.
// Setting initial state does not invoke any callbacks.
m.InitialState("locked")
// Events and their transition(s).
m.Event("coin").Transition().FromAny().To("unlocked")
m.Event("push").Transition().FromAny().To("locked")
// Transition callbacks.
m.AfterTransition().From("locked").To("unlocked").Do(func() {
turnstile.DisplayMsg = "Go"
})
m.AfterTransition().From("unlocked").To("locked").Do(func() {
turnstile.DisplayMsg = "Pay"
})
m.AfterTransition().FromAny().ToAny().Do(func() {
fmt.Printf("%s, %s\n", turnstile.GetState(), turnstile.DisplayMsg)
})
})
// Now that our turnstile is ready, let's take it for a spin:
_ = turnstile.Fire("coin") // => unlocked, Go
_ = turnstile.Fire("push") // => locked, Pay
}