JavaScript设计模式(十三):状态模式

130 阅读1分钟

介绍

状态模式:允许一个对象在其内部状态改变的时候改变它的行为。

状态模式就是对象内部的状态改变了,它的行为也会跟着改变。感觉像我们的小台灯,通电状态下会发光,断电状态就熄灭了。

实现

const OffLightState = function (light) {
  this.light = light
}
OffLightState.prototype.buttonPress = function () {
  console.log('打开弱光')
  this.light.setState(this.light.weakLightState)
}
const WeakLightState = function (light) {
  this.light = light
}
WeakLightState.prototype.buttonPress = function () {
  console.log('打开强光')
  this.light.setState(this.light.strongLightState)
}
const StrongLightState = function (light) {
  this.light = light
}
StrongLightState.prototype.buttonPress = function () {
  console.log('关灯')
  this.light.setState(this.light.offLightState)
}

const Light = function () {
  this.offLightState = new OffLightState(this)
  this.weakLightState = new WeakLightState(this)
  this.strongLightState = new StrongLightState(this)
}

Light.prototype.init = function () {
  const button = document.createElement('button')
  button.innerHTML = '开关'
  document.body.appendChild(button)
  const self = this
  self.currentState = this.offLightState
  button.addEventListener('click', () => {
    self.currentState.buttonPress()
  })
}
Light.prototype.setState = function (newState) {
  this.currentState = newState
}

const light = new Light()
light.init()

小结

感觉上状态模式跟策略模式很像,区别是策略模式中,各个策略之间是平等的,没有关系的,客户需要事先知道每个策略的作用,才能选择对应的策略。而状态模式中,状态和其对应的行为是封装好的,用户不必了解状态的细节。