有限状态机
中等 约 40 分钟
你将构建什么
一个 StateMachine 类,根据定义的状态表验证转换、拒绝非法转换并在转换时调用动作。
学习目标
- 定义状态、事件和转换表
- 验证转换并拒绝非法转换
- 在转换时执行动作(副作用)
- 跟踪当前状态和历史
前置要求
- 对象与 Map
- 函数作为值
- if/else 条件语句
步骤
- 1
定义转换表
FSM 由状态、事件和哪个事件从哪个状态移到哪个状态定义。编码为嵌套对象:transitions[fromState][event] = { to, action }。
代码const turnstileTransitions = { locked: { coin: { to: 'unlocked', action: () => console.log('Unlocking') }, push: { to: 'locked', action: () => console.log('Still locked') }, }, unlocked: { coin: { to: 'unlocked', action: () => console.log('Already unlocked') }, push: { to: 'locked', action: () => console.log('Locking') }, }, };预期结果
一个含 locked/unlocked 状态的投币旋转门转换表。
- 2
实现 StateMachine 类
类接受初始状态和转换表。存储当前状态并暴露 send(event) 触发转换。
代码class StateMachine { constructor(initial, transitions) { this.state = initial; this.transitions = transitions; this.history = [initial]; } }预期结果
一个从给定初始状态开始的 StateMachine。
- 3
实现带验证的 send
send(event) 查找 transitions[state][event]。若不存在,打印警告并返回 false(非法转换)。若存在,运行动作、更新状态并压入历史。
提示
用可选链:this.transitions[this.state]?.[event] 安全查找。
- 4
添加 canSend 守卫
添加 canSend(event),若转换存在则返回 true 而不执行。这让 UI 能为非法动作禁用按钮。
提示
查找与 send 相同,但返回布尔值而非执行。
- 5
测试旋转门 FSM
创建从 'locked' 开始的旋转门。发送 coin(→unlocked)、push(→locked)、push(从 locked 非法?不,push 保持 locked)。验证历史和非法转换被拒绝。
代码const turnstile = new StateMachine('locked', turnstileTransitions); turnstile.send('coin'); // Unlocking, state: unlocked turnstile.send('push'); // Locking, state: locked console.log('History:', turnstile.history); // ['locked', 'unlocked', 'locked'] console.log('Can coin?', turnstile.canSend('coin')); // true预期结果
输出显示转换、3 个状态的历史,canSend 返回 true。
自己动手试试
起始代码
class StateMachine {
constructor(initial, transitions) { /* TODO */ }
send(event) { /* TODO */ }
canSend(event) { /* TODO */ }
}解决方案代码
class StateMachine {
constructor(i, t) { this.state = i; this.transitions = t; this.history = [i]; }
send(e) { const tr = this.transitions[this.state]?.[e]; if (!tr) return false; tr.action?.(); this.state = tr.to; this.history.push(this.state); return true; }
canSend(e) { return !!this.transitions[this.state]?.[e]; }
}你学到了什么
你构建了有限状态机——UI 路由、游戏逻辑、解析器状态和 XState 等库背后的形式模型。FSM 让复杂状态转换可验证且无 bug。
相关资源
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。