Skip to content

状态模式 ​

对象不同状态有不同行为时,可用状态模式通过委托给不同状态对象来实现行为变化。

核心思想是每个状态封装为独立对象,行为委托给当前状态对象,可代替大量的 if-else 或 switch 语句。

适用场景 ​

  • 订单状态(待支付、已支付、已发货、已完成)。
  • 角色状态(站立、行走、奔跑、跳跃、攻击)。
  • UI组件状态,如按钮状态(正常、悬停、点击、禁用)。
  • 播放器控制,媒体状态(播放、暂停、停止、快进)。
  • 实现状态机。

电灯案例 ​

此例子中的问题:

  • press 方法违反开放-封闭原则,后续新增的状态需要改动 press 里的代码。
  • 状态切换不明显,仅表现为对 state 赋值,也无法一目了然地知道共有多少种状态。
  • 状态的切换关系通过堆砌 if-else 语句来实现,难以阅读和维护。
js
class Light {
  constructor() {
    this.state = 'off'
  }

  press() {
    if (this.state === 'off') {
      console.log('弱光')
      this.state = 'weakLight'
    } else if (this.state === 'weakLight') {
      console.log('强光')
      this.state = 'strongLight'
    } else {
      console.log('关灯')
      this.state = 'off'
    }
  }
}

const light = new Light()
light.press() // '弱光'
light.press() // '强光'
light.press() // '关灯'

状态模式重构 ​

使用状态模式重构,每种状态都封装为一个类,跟此状态相关的行为都封装都该类中。

不再使用字符串来标记状态,而是使用更立体化的状态对象,在 Light 类中为每种状态都创建一个对象,可清晰看到共有多少种装态。之后添加的新状态只需增加一个状态类,并修改下 Light 类的代码即可。

js
class OffLightState {
  constructor(light) {
    this.light = light
  }

  press() {
    console.log('弱光') // offLightState对应行为
    this.light.setState(this.light.weakLightState) // 切换状态到weakLightState
  }
}

class WeakLightState {
  constructor(light) {
    this.light = light
  }

  press() {
    console.log('强光')
    this.light.setState(this.light.strongLightState)
  }
}

class StrongLightState {
  constructor(light) {
    this.light = light
  }

  press() {
    console.log('关灯')
    this.light.setState(this.light.offLightState)
  }
}

class Light {
  constructor() {
    this.offLightState = new OffLightState(this)
    this.weakLightState = new WeakLightState(this)
    this.strongLightState = new StrongLightState(this)
    this.currentState = this.offLightState
  }

  press() {
    this.currentState.press()
  }

  setState(state) {
    this.currentState = state
  }
}

const light = new Light()
light.press() // '关灯'
light.press() // '弱光'
light.press() // '强光'

状态模式与策略模式 ​

两者相同点是都有一个上下文、一些策略或状态类,上下文把请求委托给这些类来执行。

不同点是策略模式中各策略类无关联,而状态模式中状态和状态对应的行为是封装好的,且状态间的切换也已固定。