JavaScript设计模式新实践:状态模式与复杂状态管理深度解析
一、状态模式核心原理
优雅管理复杂状态转换的面向对象方案:
// 状态基类
class OrderState {
constructor(order) {
this.order = order;
}
pay() {
throw new Error('当前状态不支持此操作');
}
cancel() {
throw new Error('当前状态不支持此操作');
}
ship() {
throw new Error('当前状态不支持此操作');
}
deliver() {
throw new Error('当前状态不支持此操作');
}
}
// 具体状态实现
class PendingState extends OrderState {
pay() {
console.log('订单支付成功');
this.order.setState(this.order.paidState);
}
cancel() {
console.log('订单已取消');
this.order.setState(this.order.cancelledState);
}
}
class PaidState extends OrderState {
ship() {
console.log('订单已发货');
this.order.setState(this.order.shippedState);
}
}
// 订单类
class Order {
constructor() {
this.pendingState = new PendingState(this);
this.paidState = new PaidState(this);
this.currentState = this.pendingState;
}
setState(state) {
this.currentState = state;
}
// 委托给当前状态
pay() {
this.currentState.pay();
}
cancel() {
this.currentState.cancel();
}
ship() {
this.currentState.ship();
}
}
// 使用示例
const order = new Order();
order.pay(); // 订单支付成功
order.ship(); // 订单已发货
order.cancel(); // 抛出错误:当前状态不支持此操作
核心优势:消除条件分支、状态封装、易于扩展、行为可预测
二、高级应用模式
1. 状态机可视化
// 状态转换可视化工具
class StateMachineVisualizer {
constructor(states) {
this.states = states;
this.transitions = {};
}
addTransition(from, to, action) {
if (!this.transitions[from]) {
this.transitions[from] = [];
}
this.transitions[from].push({ to, action });
}
visualize() {
const graph = ['stateDiagram-v2'];
for (const [from, transitions] of Object.entries(this.transitions)) {
for (const t of transitions) {
graph.push(`${from} --> ${t.to}: ${t.action}`);
}
}
return graph.join('n');
}
}
// 使用示例
const visualizer = new StateMachineVisualizer();
visualizer.addTransition('pending', 'paid', 'pay');
visualizer.addTransition('pending', 'cancelled', 'cancel');
console.log(visualizer.visualize());
// 输出Mermaid状态图语法
2. 状态持久化
// 状态持久化管理
class PersistentStateManager {
constructor(key, initialState) {
this.key = key;
this.state = this.loadState() || initialState;
}
loadState() {
const saved = localStorage.getItem(this.key);
return saved ? JSON.parse(saved) : null;
}
saveState(state) {
this.state = state;
localStorage.setItem(this.key, JSON.stringify(state));
}
getState() {
return this.state;
}
}
// 与状态模式集成
class CheckoutProcess {
constructor() {
this.stateManager = new PersistentStateManager(
'checkoutState',
{ step: 'cart', data: {} }
);
this.currentState = this.createState(this.stateManager.getState().step);
}
createState(step) {
switch(step) {
case 'cart': return new CartState(this);
case 'shipping': return new ShippingState(this);
// 其他状态...
}
}
transitionTo(stateName, data) {
this.stateManager.saveState({ step: stateName, data });
this.currentState = this.createState(stateName);
}
}
三、实战应用案例
1. 复杂表单流程管理
// 多步骤表单状态管理
class MultiStepForm {
constructor() {
this.states = {
personal: new PersonalInfoState(this),
address: new AddressState(this),
payment: new PaymentState(this)
};
this.currentState = this.states.personal;
this.data = {};
}
next() {
this.currentState.handleNext();
}
back() {
this.currentState.handleBack();
}
submit() {
this.currentState.handleSubmit();
}
render() {
return this.currentState.render();
}
}
// 具体状态实现
class PersonalInfoState {
constructor(form) {
this.form = form;
}
handleNext() {
// 验证数据...
this.form.currentState = this.form.states.address;
}
render() {
return `
`;
}
}
// 使用示例
const form = new MultiStepForm();
document.getElementById('app').innerHTML = form.render();
四、生产环境最佳实践
- 状态验证:添加状态转换前置条件检查
- 日志记录:记录状态变更历史便于调试
- 性能优化:避免在状态对象中存储大数据
- 测试策略:为每个状态编写独立单元测试
- 与Redux集成:将状态模式融入现有状态管理库