<body>
<span onclick="a('offLightState')">强光</span>
<span onclick="a('weakLightState')">关灯</span>
<span onclick="a('strongLightState')">弱光</span>
</body>
<script>
// OffLightState:
var OffLightState = function( light ){
this.light = light;
};
OffLightState.prototype.buttonWasPressed = function(){
console.log( '弱光' ); // offLightState 对应的行为
this.light.setState( this.light.weakLightState );// 切换状态到 weakLightState
};
// WeakLightState:
var WeakLightState = function( light ){
this.light = light;
};
WeakLightState.prototype.buttonWasPressed = function(){
console.log( '强光' ); // weakLightState 对应的行为
this.light.setState( this.light.strongLightState ); //切换状态到 strongLightState
};
// StrongLightState:
var StrongLightState = function( light ){
this.light = light;
};
StrongLightState.prototype.buttonWasPressed = function(){
console.log( '关灯' ); // strongLightState 对应的行为
this.light.setState( this.light.offLightState ); // 切换状态到 offLightState
};
/******************* 改写 Light 类,使用状态对象记录当前的状态 ******************/
var Light = function(){
this.offLightState = new OffLightState( this );
this.weakLightState = new WeakLightState( this );
this.strongLightState = new StrongLightState( this );
this.button = null;
};
/******************** 提供一个 方法来切换 light 对象的状态 ************************/
Light.prototype.init = function(type){
var button = document.createElement( 'button' ),
self = this;
this.currState = this[type];
this.button.onclick = function(){
self.currState.buttonWasPressed();
}
};
Light.prototype.setState = function( newState ){
this.currState = newState;
};
var light = new Light();
a = function(type){
light.init(type);
}
</script>
从以上代码可以看出,状态模式 就是 是把 可能出现的每种状态都封装成单独的类,跟此种状态有关的行为都被封装在这个类的内部。
应该就是相当于把所有情况先想到,然后出现某种情况的时候再去匹配。