状态对象、状态转移表、状态条件表、状态行为表
笔记软件在2023/4/15 9:56:38推送该笔记
状态对象、状态转移表、状态条件表、状态行为表
class stateMachine {
//状态机名称
static stateMachineName = ''
// 当前状态
static currentState = ''
// 状态对象(状态集合)
static StateTable:{
// 索引签名
[key:string]:number
} = {}
// 状态条件表(事件集合)
static COND = {}
// 状态转移表
static StateTransitionTable:any = []
// 状态行为表
static StateActionTable:{
// 索引签名
[key:string]:string
} = {}
// 根据当前状态和事件获取下一个状态
static get_state_transition(condition:string, now_statu = stateMachine.currentState):string {
return stateMachine.StateTransitionTable[stateMachine.StateTable[now_statu]][condition];
}
// 执行迁移状态,会修改现在状态,并执行迁移函数
static move_status(statu:string) :string{
let callback = stateMachine.StateActionTable[statu];
stateMachine.currentState = statu; //改状态
if (callback == undefined) {
throw ('无处理函数')
}
// 返回执行动作
return callback;
}
}
测试
// 测试
stateMachine.stateMachineName = 'test stateMachine'
stateMachine.currentState = 'STA_START'
stateMachine.StateTable = {
STA_START: 0,
STA_U1: 1,
STA_U2: 2,
STA_L1: 3,
STA_END: 4,
STA_ERROR: 5,
}
stateMachine.COND = {
upper: 0,
lower: 1,
end: 2,
}
stateMachine.StateTransitionTable = [
//事件: upper,lower,end
['STA_U1', 'STA_L1', 'STA_END'], //START
['STA_U2', 'STA_L1', 'STA_END'], //U1
['STA_U2', 'STA_L1', 'STA_END'], //U2
['STA_U1', 'STA_L1', 'STA_END'], //L1
]
stateMachine.StateActionTable = {
'STA_U1': 'do_u1',
'STA_U2': 'do_u2',
'STA_L1': 'do_l1',
}
// 测试部分
console.log(stateMachine)
console.log(stateMachine.currentState)
stateMachine.move_status(stateMachine.get_state_transition('1'))
console.log(stateMachine.currentState)
stateMachine.move_status(stateMachine.get_state_transition('0'))
console.log(stateMachine.currentState)
stateMachine.move_status(stateMachine.get_state_transition('0'))
console.log(stateMachine.currentState)