zhangdizhangdi

状态模式 📖

定义

状态模式(State Pattern),允许一个对象在其内部状态改变时改变它的行为,对象看起来似乎修改了它的类。

实现

js
class TrafficLight {
  count = 0
  currentState = new Red(this)

  change(state) {
    // limits number of changes
    if (this.count++ >= 10) return
    this.currentState = state
    this.currentState.go()
  }

  start() {
    this.currentState.go()
  }
}

class Red {
  constructor(light) {
    this.light = light
  }
  go() {
    console.log('Red --> for 1 minute')
    this.light.change(new Green(this.light))
  }
}

class Yellow {
  constructor(light) {
    this.light = light
  }
  go() {
    console.log('Yellow --> for 10 seconds')
    this.light.change(new Red(this.light))
  }
}

class Green {
  constructor(light) {
    this.light = light
  }
  go() {
    console.log('Green --> for 1 minute')
    light.change(new Yellow(this.light))
  }
}

const light = new TrafficLight()
light.start()
执行结果
Red --> for 1 minute
Green --> for 1 minute
Yellow --> for 10 seconds
Red --> for 1 minute
Green --> for 1 minute
Yellow --> for 10 seconds
Red --> for 1 minute
Green --> for 1 minute
Yellow --> for 10 seconds
Red --> for 1 minute
Green --> for 1 minute

参考