项目作者: ThibaultRiviere

项目描述 :
FSM library
高级语言: Go
项目地址: git://github.com/ThibaultRiviere/go-fsm.git
创建时间: 2017-02-04T13:45:10Z
项目社区:https://github.com/ThibaultRiviere/go-fsm

开源协议:MIT License

下载


go-fsm

FSM library to create a finite-state-machine

Documentation

See: go-fsm Documentation

Getting Started

Installing

To start using go-fsm, install Go and run go get:

  1. $ go get github.com/ThibaultRiviere/go-fsm

Creating a new go-fsm

  1. import (
  2. "fmt"
  3. "github.com/ThibaultRiviere/go-fsm"
  4. )
  5. func main() {
  6. states := []string{"locked", "close", "open"}
  7. defaultState := "close"
  8. door, err := fsm.New(states, defaultState)
  9. }

Adding a new transition

  1. // transition name, state needed, next state, handler
  2. door.AddTransition("unlock door", "locked", "close", func() {
  3. fmt.Println("The door have been unlock")
  4. })

Handle a transition

  1. currentState, err := door.HandleTransition("unlock door")
  2. if err != nil {
  3. fmt.Println("Couldn't unlock the door because the state is ", currentState)
  4. } else {
  5. fmt.Println("The door state now is ", currentState)
  6. }

If the current state is locked, then the door will be unlock and the current state will be change to close.
In case where the current state is not lock then the transition unlock door will failed returning an error and the current state of the door.

Adding a new Action

  1. // action name, state needed, handler
  2. door.AddAction("travers door", "open", func() {
  3. fmt.Println("Someone go through the door")
  4. })

Handle an action

  1. err := door.HandleAction("travers door")
  2. if err != nil {
  3. fmt.Println("Impossible to travers the door"
  4. } else {
  5. fmt.Println("New people in the room")
  6. }

If the current state of the door is open, then it’s possible to go through the door and enter in the room.

Errors

  • ErrUnknowState when using an undefined state

    1. fsm, err := fsm.New([]string{"a", "b"}, "b")
    2. fsm.addAction("oups", "c")
  • ErrUnknowAction when using an undefined action

    1. fsm, err := fsm.New([]string{"a", "b"}, "b")
    2. fsm.HandleAction("Action is not define")
  • ErrUnknowTransition when using an undefined transition

    1. fsm, err := fsm.New([]string{"a", "b"}, "b")
    2. fsm.HandleTransition("Transition is not define")
  • ErrBadState current state is not the state needed for the action/transition

    1. fsm, err := fsm.New([]string{"a", "b"}, "b")
    2. fsm.AddAction("test", "a", func() {
    3. fmt.Println("this is an action")
    4. })
    5. fsm.HandleAction("test")

License

MIT