get
方法用于获取状态机当前的状态。
stateMachine.get()
该方法不接受任何参数。
返回值为当前状态机的状态,如果状态机还没有设置过状态,则返回 undefined
。
const states = {
idle: 'Idle State',
running: 'Running State',
stopped: 'Stopped State'
};
const transitions = [
{ name: 'start', from: 'idle', to: 'running' },
{ name: 'stop', from: 'running', to: 'stopped' },
{ name: 'restart', from: 'stopped', to: 'running' }
];
const stateMachine = new StateMachine({ states, transitions });
console.log(stateMachine.get()); // Output: undefined
stateMachine.start();
console.log(stateMachine.get()); // Output: Running State
stateMachine.stop();
console.log(stateMachine.get()); // Output: Stopped State
在上面的代码中,我们首先定义了状态集合 states
和状态转换集合 transitions
。
然后我们创建了一个状态机 stateMachine
。
我们调用 get
方法,发现状态机还没有设置过状态,返回 undefined
。
接着我们调用 start
方法来设置状态机的状态为 running
。
我们再次调用 get
方法,返回值为 Running State
。
最后我们调用 stop
方法来将状态机的状态设置为 stopped
。
我们再次调用 get
方法,返回值为 Stopped State
。