javascript设计模式——状态模式

状态模式即是解决程序中臃肿的分支判断语句问题,将每个分支转化为一种状态独立出来,方便每种状态的管理又不至于每次执行时遍历所有分支。在程序中到底产生哪种行为结果,决定与选择哪种状态,而选择何种状态又是在程序运行时决定的。当然状态模式最终的目的即是简化分支判断流程。

分支判断模式实现

  // 实现超级玛丽,因为她有很多东西,走,跳,射击,如果用if或者switch判断,造成很多判断分支
  // 单动作条件判断,每增加一个动作要添加一个判断
  var lastAction = ''
  function changeMarry(action) {
    if (action === 'jump') {

    } else if (action === 'move') {

    } else {

    }
    lastAction = action
  }
  // 复合动作对条件判断的开销是翻倍的
  var lastAction1 = ''
  var lastAction2 = ''
  function changeMarry(action1, action2) {
    if (action1 === 'shoot') {

    } else if (action1 === 'jump') {

    } else if (action1 === 'move' && action2 === 'shoot') {

    } else if (action1 === 'jump' && action2 === 'shoot') {

    }
    lastAction1 = action1 || ''
    lastAction2 = action2 || ''
  }

使用状态模式实现

    var MarryState = function () {
      var _currentState = {},
        states = {
          jump: function () {
            console.log('jump')
          },
          move: function () {
            console.log('move')
          },
          shoot: function () {
            console.log('shoot')
          },
          squat: function () {
            console.log('squat')
          }
        }
      var Action = {
        changeState: function () {
          var arg = arguments
          _currentState = {}
          if (arg.length) {
            for (var i = 0, len = arg.length; i < len; i++) {
              _currentState[arg[i]] = true
            }
          }
          return this
        },
        goes: function () {
          console.log("触发一次动作")
          for (var i in _currentState) {
            states[i] && states[i]()
          }
          return this
        }
      }
      return {
        change: Action.changeState,
        goes: Action.goes
      }
    }
    MarryState().change('jump', 'shoot')
    .goes()
    .goes()
    .change('shoot')
    .goes()

你可能感兴趣的:(javascript设计模式——状态模式)