专业编程教程与实战项目分享平台

网站首页 > 技术文章 正文

高级前端必会设计模式之状态模式

ins518 2024-09-11 09:27:17 技术文章 26 ℃ 0 评论

前端JavaScript设计模式-状态模式:

状态模式的功能是区分事物内部的状态,把多种状态变化以及变化之后的逻辑单独分出来做,而不是一直写if-else来运行程序

以实际应用场景修改灯泡颜色来做案例

// 定义事物状态
class State{
  constructor(color){
    this.color = color
  }
  handle(context){
    console.log(`true to ${this.color} light`)
    context.setState(this)
  }
}

class Context{
  constructor(){
    this.state = null
  }
  getState(){
    return this.state
  }
  setState(state){
    this.state = state
  }
}

let context = new Context()

let blue = new State('blue')
let yellow = new State('yellow')
let red = new State('red')

// 通过改变状态显示灯泡不同颜色
blue.handle(context)
console.log(context.getState())
yellow.handle(context)
console.log(context.getState())
red.handle(context)
console.log(context.getState())

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表