答案:javaScript通过定义状态和事件实现有限状态机,核心是封装状态转换逻辑。使用类可复用FSM,支持配置化与钩子函数,适用于订单、表单等复杂流程管理,提升代码可维护性。

用javascript实现有限状态机(Finite State machine, FSM)能有效管理复杂流程,比如订单处理、表单向导、游戏角色行为等。核心思路是把系统拆分为明确的状态和状态之间的转换规则,避免散乱的条件判断。
定义状态和事件
每个FSM由一组状态、一组事件和一套转移规则组成。例如一个订单可能有“待支付”、“已支付”、“发货中”、“已完成”等状态,触发事件包括“支付”、“发货”、“完成”。
const stateMachine = {
currentState: ‘pending’,
states: {
pending: [‘pay’],
paid: [‘ship’],
shipped: [‘deliver’],
delivered: []
}
};
实现状态转移逻辑
通过方法控制状态变更,确保只允许合法的转换。每次触发事件时检查当前状态是否支持该事件。
立即学习“Java免费学习笔记(深入)”;
function transition(Event) {
const allowedEvents = stateMachine.states[stateMachine.currentState];
if (!allowedEvents.includes(event)) {
console.warn(`不允许在状态 ${stateMachine.currentState} 下执行 ${event}`);
return false;
}
switch (event) {
case ‘pay’:
stateMachine.currentState = ‘paid’;
break;
case ‘ship’:
stateMachine.currentState = ‘shipped’;
break;
case ‘deliver’:
stateMachine.currentState = ‘delivered’;
break;
}
console.log(‘当前状态:’, stateMachine.currentState);
return true;
}
封装为可复用类
将状态机封装成类,便于在多个场景使用。支持传入配置,提升灵活性。
class FiniteStateMachine {
constructor(config) {
this.currentState = config.initial;
this.transitions = config.transitions; // { state: { event: newState } }
}
can(event) {
return !!this.transitions[this.currentState]?.[event];
}
transition(event) {
const nextState = this.transitions[this.currentState]?.[event];
if (!nextState) {
throw new Error(`无效转换: ${this.currentState} + ${event}`);
}
this.currentState = nextState;
return this.currentState;
}
}
使用示例:
const orderFSM = new FiniteStateMachine({
initial: ‘pending’,
transitions: {
pending: { pay: ‘paid’ },
paid: { ship: ‘shipped’ },
shipped: { deliver: ‘delivered’ }
}
});
orderFSM.transition(‘pay’); // ‘paid’
orderFSM.transition(‘ship’); // ‘shipped’
扩展功能:钩子与异步处理
实际项目中可在状态变更前后添加钩子函数,比如记录日志、调用API。
class EnhancedFSM {
constructor(config) {
this.currentState = config.initial;
this.transitions = config.transitions;
this.onEnter = config.onEnter || {};
}
async transition(event) {
const nextState = this.transitions[this.currentState]?.[event];
if (!nextState) throw new Error(‘非法转移’);
this.currentState = nextState;
if (this.onEnter[nextState]) {
await this.onEnter[nextState]();
}
return nextState;
}
}
基本上就这些。用FSM管理流程,代码更清晰,边界情况更容易控制。不复杂但容易忽略设计,建议配合可视化工具或配置文件维护状态图。


