Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
yangrenmu opened this issue Sep 22, 2020 · 0 comments
Open

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

yangrenmu opened this issue Sep 22, 2020 · 0 comments
Labels

Comments

@yangrenmu
Copy link
Owner

介绍

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

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

实现

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()

小结

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

@yangrenmu yangrenmu added the mode label Sep 22, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant