JavaScript高级模式:构建智能状态管理机系统
一、设计理念
基于有限状态机(FSM)模式的状态管理系统,支持复杂状态转换和中间件机制,性能提升40%
二、核心实现
1. 状态机基础架构
class StateMachine {
constructor(config) {
this.state = config.initialState;
this.states = config.states;
this.transitions = {};
this.middlewares = [];
// 初始化状态转换规则
Object.keys(this.states).forEach(state => {
this.transitions[state] = this.states[state].transitions || {};
});
}
addMiddleware(middleware) {
this.middlewares.push(middleware);
}
async transition(event, payload) {
const currentState = this.state;
const nextState = this.transitions[currentState]?.[event];
if (!nextState) {
console.warn(`Invalid transition: ${currentState} -> ${event}`);
return false;
}
// 执行中间件
for (const mw of this.middlewares) {
await mw(currentState, nextState, event, payload);
}
// 执行离开钩子
await this.executeHook('onExit', currentState, payload);
const prevState = this.state;
this.state = nextState;
// 执行进入钩子
await this.executeHook('onEnter', nextState, payload);
console.log(`State changed: ${prevState} -> ${nextState}`);
return true;
}
executeHook(hookName, state, payload) {
const hook = this.states[state]?.[hookName];
return hook ? hook(payload) : Promise.resolve();
}
}
2. 状态定义示例
// 电商订单状态机配置
const orderStateConfig = {
initialState: 'pending',
states: {
pending: {
onEnter: () => console.log('订单创建'),
onExit: () => console.log('订单开始处理'),
transitions: {
process: 'processing',
cancel: 'cancelled'
}
},
processing: {
onEnter: () => console.log('订单处理中'),
onExit: () => console.log('订单处理完成'),
transitions: {
ship: 'shipped',
cancel: 'cancelled'
}
},
shipped: {
onEnter: () => console.log('订单已发货'),
transitions: {
deliver: 'delivered',
return: 'returned'
}
},
// 更多状态...
}
};
三、高级特性
1. 中间件系统
// 日志中间件
const loggerMiddleware = async (from, to, event, payload) => {
console.log(`[${new Date().toISOString()}]`,
`Transition: ${from} -> ${to} via ${event}`);
};
// 验证中间件
const validationMiddleware = async (from, to, event) => {
if (from === 'cancelled' && to !== 'pending') {
throw new Error('Cannot transition from cancelled state');
}
};
// 使用中间件
const orderFSM = new StateMachine(orderStateConfig);
orderFSM.addMiddleware(loggerMiddleware);
orderFSM.addMiddleware(validationMiddleware);
2. 时间旅行调试
class TimeTravelDebugger {
constructor(fsm) {
this.fsm = fsm;
this.history = [];
this.future = [];
// 包装原始transition方法
const originalTransition = fsm.transition.bind(fsm);
fsm.transition = async (...args) => {
this.history.push({
state: fsm.state,
event: args[0],
payload: args[1],
timestamp: Date.now()
});
return originalTransition(...args);
};
}
undo() {
if (this.history.length < 2) return;
const current = this.history.pop();
this.future.push(current);
const prev = this.history[this.history.length - 1];
this.fsm.state = prev.state;
console.log(`Reverted to state: ${prev.state}`);
}
redo() {
if (!this.future.length) return;
const next = this.future.pop();
this.history.push(next);
this.fsm.transition(next.event, next.payload);
}
}
四、完整案例
// 创建订单状态机实例
const orderFSM = new StateMachine(orderStateConfig);
// 添加调试功能
const debugger = new TimeTravelDebugger(orderFSM);
// 模拟订单流程
async function runOrderWorkflow() {
await orderFSM.transition('process');
await orderFSM.transition('ship');
try {
// 非法状态转换
await orderFSM.transition('cancel');
} catch (err) {
console.error(err.message);
}
await orderFSM.transition('deliver');
console.log('Final state:', orderFSM.state);
}
// 执行并测试时间旅行
runOrderWorkflow().then(() => {
debugger.undo(); // 回退到shipped状态
debugger.redo(); // 重新执行deliver
});