package model import ( "rocommon/util" ) type StateMachine interface { SwitchState(state int32, data interface{}) RegisterState(state int32, proc StateProcessor) bool GetState() int32 } const MAX_RECURSIVE = 16 //最大递归层数 type StateProcessor func(sm *StateMachineCore, data interface{}) int32 type StateMachineCore struct { procMap map[int32]StateProcessor state int32 //状态 } func (this *StateMachineCore) InitState() { this.procMap = map[int32]StateProcessor{} this.state = 0 } //状态机切换 func (this *StateMachineCore) SwitchState(state int32, data interface{}) { this.state = this.procState(state, 1, data) } func (this *StateMachineCore) RegisterState(state int32, proc StateProcessor) bool { if _, ok := this.procMap[state]; ok { util.ErrorF("StateMachineCore has been register") this.procMap[state] = proc return true } this.procMap[state] = proc return true } func (this *StateMachineCore) GetState() int32 { return this.state } //返回值表示下一个状态 func (this *StateMachineCore) DoState(state int32, data interface{}) int32 { return this.procState(state, 1, data) } //num表示递归累加次数 func (this *StateMachineCore) procState(state int32, num int32, data interface{}) int32 { if num >= MAX_RECURSIVE { util.PanicF("State machine reach max MAX_RECURSIVE") return state } if this.GetState() == state { return state } if len(this.procMap) <= 0 { return state } if proc, ok := this.procMap[state]; !ok { return state } else { newState := proc(this, data) if newState != state { return this.procState(newState, num+1, data) } return state } }