当一个对象或按钮有多个方法,多个状态,状态之间可以切换时,如果使用if-else实现,代码将充斥if-else,使得代码难以阅读,修改困难。此时使用状态模式,将对象的每一个状态编写为一个状态对象,且状态对象都提供同名的方法,原对象将事件委托给对应的状态对象实现。
var delegate = function( client, delegation ){
return {
buttonWasPressed: function(){ // 将客户的操作委托给delegation对象
return delegation.buttonWasPressed.apply( client, arguments );
}
}
};
var FSM = {
off: {
buttonWasPressed: function(){
console.log('关灯');
this.button.innerHTML = '下一次按我是开灯';
this.currState = this.onState;
}
},
on: {
buttonWasPressed: function(){
console.log('开灯');
this.button.innerHTML = '下一次按我是关灯';
this.currState = this.offState;
}
}
};
var Light = function(){
this.offState = delegate( this, FSM.off );
this.onState = delegate( this, FSM.on );
this.currState = this.offState; //设置初始状态为关闭状态
this.button = null;
}
Light.prototype.init = function(){
var button = document.createElement('button'),
self = this;
button.innerHTML = '已关灯';
this.button = document.body.appendChild( button );
this.button.onclick = function(){
self.currState.buttonWasPressed();
}
}
var light = new Light();
light.init();