状态模式的关键是区分事物内部的状态,事物内部状态改变往往会带来事物的行为改变
初识状态模式
状态模式的关键是把事物的每种状态封装成单独的类,跟此种状态有关的行为都被封装在这个类的内部。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| var light = function(){ this.state = 'off'; 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.buttonWasPressed(); } };
light.prototype.buttonWasPressed = function(){ if(this.state === 'off'){ console.log('开灯'); this.state = 'on'; }else{ console.log('关灯'); this.state = 'off'; } };
var light = new light(); light.init();
|
以上程序会在状态多的时候会变得臃肿,破坏开放封闭原则(每增加一种状态,就要改变buttonWasPressed
里的代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
|
var OfflightState = function(light){ this.light = light; };
OfflightState.prototype.buttonWasPressed = function(){ console.log('弱光'); this.light.setState(this.light.weakLightState); };
var WeakLightState = function(light){ this.light = light; };
WeakLightState.prototype.buttonWasPressed = function(){ console.log('强光'); this.light.setState(this.light.strongLightState); };
var StrongLightState = function(light){ this.light = light; };
StrongLightState.prototype.buttonWasPressed = function(){ console.log('关灯'); this.light.setState(this.light.offLightState); };
var light = function(){ this.offLightState = new OfflightState(this); this.weakLightState = new WeakLightState(this); this.strongLightState = new StrongLightState(this); this.button = null; };
light.prototype.init = function(){ var button = document.createElement('button'), self = this;
button.innerHTML = '开关'; this.button = document.body.appendChild(button);
this.curState = this.offLightState; this.button.onclick = function(){ self.curState.buttonWasPressed(); } }
light.prototype.setState = function(newState){ this.curState = newState; }
var light = new light(); light.init();
|
状态模式的定义