前端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())
本文暂时没有评论,来添加一个吧(●'◡'●)