easyfsm

package module
v0.0.0-...-c67e1bb Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 29, 2024 License: MIT Imports: 3 Imported by: 0

README

easyfsm

English | 简体中文

Project Overview

This is a simple state machine implemented in Go that supports state transitions based on conditional expressions. The state machine can dynamically switch between multiple states based on different events and conditions. It is suitable for scenarios that require state management based on specific conditions, such as workflow engines, game state management, user permission control, and more.

Features

  • Condition-Driven State Transitions: Supports controlling state transitions through conditional expressions.
  • Flexible State Definitions: Allows the definition of an arbitrary number of states and events, supporting various state transition logic.
  • Easy to Extend: The code structure is clear, making it easy to add new features and states.

Example Code

Here is a simple example of the state machine implementation:

func TestConditionTran(t *testing.T) {
	testInit()
	fsm, err := NewFsm("order_test", 40)
	if err != nil {
		t.Error(err)
	}
	para := make(map[string]interface{})
	para["customer_received"] = 0
	err = fsm.Tran("OrderDeliveredEt", para)
	if err != nil {
		t.Error(err)
	}
	if fsm.curState != 60 {
		t.Error("curState is not 60")
	}
}

Contribution

Contributions are welcome! Please submit pull requests or create issues for bugs or suggestions.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Init

func Init(bizDescMap map[string]BizDesc) error

程序启动时 初始化状态机

Types

type BizDesc

type BizDesc struct {
	Transitions []Transition
}

type DstState

type DstState struct {
	State
	CondExpr string // 状态转移条件
}

type Fsm

type Fsm struct {
	// contains filtered or unexported fields
}

状态机

func NewFsm

func NewFsm(biz string, curState int) (*Fsm, error)

func (*Fsm) CanTran

func (f *Fsm) CanTran(event string) bool

true 意味着可以转移到下一个状态

func (*Fsm) CurState

func (f *Fsm) CurState() int

func (*Fsm) Tran

func (f *Fsm) Tran(event string, paras map[string]interface{}) error

状态转移

type SrcEventKey

type SrcEventKey struct {
	SrcState int
	Event    string
}

type State

type State struct {
	StateId   int
	StateName string
	Type      StateType // 使用 StateType 类型
}

func NewState

func NewState(stateId int, stateName string, opts ...StateOption) State

type StateOption

type StateOption func(*State)

func WithType

func WithType(stateType StateType) StateOption

type StateType

type StateType int8
const (
	StartState  StateType = 1 // 开始节点
	EndState    StateType = 2 // 结束节点
	CancelState StateType = 3 // 取消节点
)

type Transition

type Transition struct {
	Event string
	Src   []State
	Dst   []DstState
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL