state_machine.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package model
  2. import (
  3. "rocommon/util"
  4. )
  5. type StateMachine interface {
  6. SwitchState(state int32, data interface{})
  7. RegisterState(state int32, proc StateProcessor) bool
  8. GetState() int32
  9. }
  10. const MAX_RECURSIVE = 16 //最大递归层数
  11. type StateProcessor func(sm *StateMachineCore, data interface{}) int32
  12. type StateMachineCore struct {
  13. procMap map[int32]StateProcessor
  14. state int32 //状态
  15. }
  16. func (this *StateMachineCore) InitState() {
  17. this.procMap = map[int32]StateProcessor{}
  18. this.state = 0
  19. }
  20. //状态机切换
  21. func (this *StateMachineCore) SwitchState(state int32, data interface{}) {
  22. this.state = this.procState(state, 1, data)
  23. }
  24. func (this *StateMachineCore) RegisterState(state int32, proc StateProcessor) bool {
  25. if _, ok := this.procMap[state]; ok {
  26. util.ErrorF("StateMachineCore has been register")
  27. this.procMap[state] = proc
  28. return true
  29. }
  30. this.procMap[state] = proc
  31. return true
  32. }
  33. func (this *StateMachineCore) GetState() int32 {
  34. return this.state
  35. }
  36. //返回值表示下一个状态
  37. func (this *StateMachineCore) DoState(state int32, data interface{}) int32 {
  38. return this.procState(state, 1, data)
  39. }
  40. //num表示递归累加次数
  41. func (this *StateMachineCore) procState(state int32, num int32, data interface{}) int32 {
  42. if num >= MAX_RECURSIVE {
  43. util.PanicF("State machine reach max MAX_RECURSIVE")
  44. return state
  45. }
  46. if this.GetState() == state {
  47. return state
  48. }
  49. if len(this.procMap) <= 0 {
  50. return state
  51. }
  52. if proc, ok := this.procMap[state]; !ok {
  53. return state
  54. } else {
  55. newState := proc(this, data)
  56. if newState != state {
  57. return this.procState(newState, num+1, data)
  58. }
  59. return state
  60. }
  61. }