JavaScript高级模式:构建智能状态管理机系统

2025-07-24 0 390

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
});
JavaScript高级模式:构建智能状态管理机系统
收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

淘吗网 javascript JavaScript高级模式:构建智能状态管理机系统 https://www.taomawang.com/web/javascript/638.html

常见问题

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务