// 定义基础状态机类
class BaseStateMachine {
constructor(initialState) {
this.currentState = initialState;
}
// 转换状态的方法,子类需要根据实际逻辑重写此方法
transition(event) {
throw new Error("transition method must be implemented in subclass");
}
}
// 定义开关机状态机
class ToggleMachine extends BaseStateMachine {
transition(event) {
switch (this.currentState) {
case 'off':
if (event === 'toggle') this.currentState = 'on';
break;
case 'on':
if (event === 'toggle') this.currentState = 'off';
break;
default:
console.log('Invalid event for ToggleMachine');
}
console.log(`ToggleMachine is now ${this.currentState}`);
}
}
// 定义门开关状态机
class DoorMachine extends BaseStateMachine {
transition(event) {
switch (this.currentState) {
case 'closed':
if (event === 'open') this.currentState = 'open';
break;
case 'open':
if (event === 'close') this.currentState = 'closed';
break;
default:
console.log('Invalid event for DoorMachine');
}
console.log(`DoorMachine is now ${this.currentState}`);
}
}
// 定义停止与启动状态机
class StopStartMachine extends BaseStateMachine {
transition(event) {
switch (this.currentState) {
case 'stopped':
if (event === 'start') this.currentState = 'running';
break;
case 'running':
if (event === 'stop') this.currentState = 'stopped';
break;
default:
console.log('Invalid event for StopStartMachine');
}
console.log(`StopStartMachine is now ${this.currentState}`);
}
}
// 创建状态机实例
const toggleMachine = new ToggleMachine('off');
const doorMachine = new DoorMachine('closed');
const stopStartMachine = new StopStartMachine('stopped');
// 定义状态机数组
const stateMachinesArray = [toggleMachine, doorMachine, stopStartMachine];
// 触发状态转换示例
stateMachinesArray[0].transition('toggle'); // 应输出: ToggleMachine is now on
stateMachinesArray[1].transition('open'); // 应输出: DoorMachine is now open
stateMachinesArray[2].transition('start'); // 应输出: StopStartMachine is now running
标签:break,javascript,定义,transition,状态机,event,currentState,log
From: https://blog.csdn.net/m0_60329232/article/details/139329839