状态模式

2018-09-19  本文已影响0人  康乐芳华
window.onload = function () {
  (function () {
    var State = function () {}
    State.prototype.buttonWasPressed = function () {
      console.warn("子类必须实现 buttonWasPressed 方法")
    }
    // 关灯状态
    var OffLightState = function (light) {
      this.light = light;
      this.stateName = 'OFF'
    }
    OffLightState.prototype = new State();
    OffLightState.prototype.buttonWasPressed = function () {
      console.log('turn to weak')
      this.light.setState(this.light.weakLightState)
    }

    // 弱光状态
    var WeakLightState = function (light) {
      this.light = light;
      this.stateName = 'WEAK'
    }
    WeakLightState.prototype = new State();
    WeakLightState.prototype.buttonWasPressed = function () {
      console.log('turn to strong')
      this.light.setState(this.light.strongLightState)
    }

    // 强光状态
    var StrongLightState = function (light) {
      this.light = light;
      this.stateName = 'STRONG'
    }
    StrongLightState.prototype = new State();
    StrongLightState.prototype.buttonWasPressed = function () {
      console.log('turn to off')
      this.light.setState(this.light.offLightState)
    }


    var Light = function () {
      this.offLightState = new OffLightState(this)
      this.weakLightState = new WeakLightState(this)
      this.strongLightState = new StrongLightState(this)
    }
    Light.prototype.setState = function (newState) {
      this.currState = newState;
    }


    Light.prototype.init = function () {
      this.button = document.createElement('button')
      var self = this;
      document.body.appendChild(this.button)
      this.currState = this.offLightState;
      this.button.innerText = this.currState.stateName;
      this.button.onclick = function () {
        self.currState.buttonWasPressed()
        self.button.innerText = self.currState.stateName;
      }
    }

    var light = new Light();
    light.init()
  })()
}
上一篇 下一篇

猜你喜欢

热点阅读