介绍
示例
UML类图
点击查看【processon】
代码
// 状态 红灯/绿灯/黄灯
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
}
}
const context = new Context()
const red = new State('red')
const blue = new State('blue')
const yellow = new State('yellow')
red.handle(context)
yellow.handle(context)
blue.handle(context)
console.log(context.getState())
场景