在javascript中定义三个状态机

// 定义基础状态机类
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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值