前面介绍了Js开发的有限状态机,这里介绍一下这个有限状态机涉及的基本概念——状态(State)和转移(Transition)。下面是说明状态和转移简单的例子,说明了固体液体和气体之间的状态转换:
var fsm = new StateMachine({
init: 'solid',
transitions: [
{ name: 'melt', from: 'solid', to: 'liquid' },
{ name: 'freeze', from: 'liquid', to: 'solid' },
{ name: 'vaporize', from: 'liquid', to: 'gas' },
{ name: 'condense', from: 'gas', to: 'liquid' }
]
});
状态之间的转换动作可以是相同的,比如我们用按钮控制灯的开关,如果灯是打开状态,那么按一下就变为关闭,再按一下就变为打开,那么用状态机可以写为:
var fsm = new StateMachine({
init: 'opened',
transitions: [
{ name: 'push', from: 'opened', to: 'closed' },
{ name: 'push', from: 'closed', to: 'opened' }
]
});
也有可能一个动作可以使不同的状态转变到同一个状态,比如重置动作,这种情况下,可以在from中使用多个状态:
{ name: 'reset', from: [ 'B', 'C', 'D' ], to: 'A' }
网友评论