Created
March 16, 2018 22:48
-
-
Save mrzahrada/aa9324f0c8413fe1fb9e12b83587e795 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"log" | |
"time" | |
) | |
// State contains current state | |
type State struct { | |
input []byte | |
} | |
// StateFn defines transition | |
type StateFn func(*State) StateFn | |
// NewPassState creates Pass state | |
func NewPassState(next StateFn) StateFn { | |
return func(_ *State) StateFn { | |
log.Println("[DEBUG] Entering pass state") | |
log.Println("[DEBUG] Exiting pass state") | |
return next | |
} | |
} | |
// NewWaitDelayState creates Wait state | |
func NewWaitDelayState(next StateFn, delay time.Duration) StateFn { | |
return func(_ *State) StateFn { | |
log.Println("[DEBUG] Entering wait state") | |
time.Sleep(delay) | |
log.Println("[DEBUG] Exiting wait state") | |
return next | |
} | |
} | |
// Run state machine | |
func Run(startState StateFn, input []byte) { | |
state := &State{input} | |
for stateFn := startState; stateFn != nil; { | |
stateFn = stateFn(state) | |
} | |
} | |
func main() { | |
state2 := NewPassState(nil) | |
state1 := NewWaitDelayState(state2, time.Second*5) | |
Run(state1, []byte{}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment