前面我们创建一个有限状态机都是直接使用构造函数,比如:
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 Matter = StateMachine.factory({ // <-- the factory is constructed here
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 a = new Matter(), // <-- instances are constructed here
b = new Matter(),
c = new Matter();
需要注意的是,使用工厂方法创建的实例数据是共享的,这并不是我们希望的,为了保持实例中数据的独立性,需要使用方法定义数据,比如:
data: function(color) { // <-- use a method that can be called for each instance
return {
color: color
}
},
不能使用下面的方式定义:
data: {
color: 'red'
},
我们还可以在现有的对象上增加状态机的功能,比如:
var component = { /* ... */ };
StateMachine.apply(component, {
init: 'A',
transitions: {
{ name: 'step', from: 'A', to: 'B' }
}
});
网友评论