js设计模式---状态模式补充

 
<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>
 

  从以上代码可以看出,状态模式 就是 是把 可能出现的每种状态都封装成单独的类,跟此种状态有关的行为都被封装在这个类的内部。

应该就是相当于把所有情况先想到,然后出现某种情况的时候再去匹配。

 

参考文档:https://juejin.im/post/5c23725bf265da61764aedc7

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值