设计模式 十 状态模式

123 阅读1分钟

介绍

一个对象有状态变化

每次状态变化都出发一个逻辑

不能总是使用 if else 控制

image.png

class State{
     constructor(color){
         this.color = color
     }
     handle(context){
         console.log(`turn 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()

 const green = new State('green')
 const yellow = new State('yellow')
 const red = new State('red')

 green.handle(context)
 yellow.handle(context)
 red.handle(context)

场景

有限状态机

github.com/taoqf/javas…

image.png

image.png

设计模式验证

将状态对象和主题对象分离,状态的变化逻辑单独处理,符合开放封闭原则