美文网首页
状态模式

状态模式

作者: 康乐芳华 | 来源:发表于2018-09-19 14:09 被阅读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()
  })()
}

相关文章

  • State模式

    状态模式(State模式) 定义 状态模式,又称状态对象模式(Pattern of Objects for S...

  • 设计模式-状态模式

    设计模式-状态模式 设计模式 状态模式的关键是区分事物内部的状态

  • 状态模式(状态机模式)

    状态模式学习笔记 前言:文章从三方面简单阐述状态模式:是什么、为什么、如何做。这是我在工作之余自己的一些理解、思考...

  • C++设计模式(3)

    本文预览: 状态模式 组合模式 迭代器 职责链 命令 状态模式 定义:状态模式(State Pattern),允许...

  • 设计模式——状态模式

    定义 状态模式,又称状态对象模式(Pattern of Objects for States),状态模式是对象的行...

  • 第5章 -行为型模式-状态模式

    一、状态模式的简介 二、状态模式的优缺点 三、状态模式的实例

  • 状态模式

    Android进阶之设计模式 状态模式 定义: 当一个对象的内在状态改变时允许改变其行为,这个对象看起来像是改变了...

  • 状态模式

    状态模式:允许对象在内部状态改变时改变它的行为,对象看起来好像修改了它的类。允许对象随着状态改变而改变行为。 策略...

  • 状态模式

    《大话设计模式》阅读笔记和总结。原书是C#编写的,本人用Java实现了一遍,包括每种设计模式的UML图实现和示例代...

  • 状态模式

    状态模式 一个对象有状态变化 每次状态变化都会触发一个逻辑 不能总是用 if...else 来控制 示例 交通灯信...

网友评论

      本文标题:状态模式

      本文链接:https://www.haomeiwen.com/subject/bjlinftx.html