状态模式
- 一个对象有状态变化
- 每次状态变化都会触发一个逻辑
- 不能总是用 if...else 来控制
示例
- 交通灯信号灯的不同状态
UML

- State 的抽离也许会想不到
// 状态 (红灯, 绿灯, 黄灯)
class State {
constructor(color) {
this.color = color;
}
handle(context) {
console.log(`turn to ${this.color} light`);
context.setState(this);
}
}
// 主体
class Contest {
constructor() {
this.state = null;
}
// 获取状态
getState() {
return this.state;
}
setState(state) {
this.state = state;
}
}
// test
const context = new Contest();
const green = new State("green");
const yellow = new State("yellow");
const red = new State("red");
// 绿灯
green.handle(context);
console.log(context.getState());
// 黄灯
yellow.handle(context);
console.log(context.getState());
// 红灯
red.handle(context);
console.log(context.getState());
- 状态和主体的分离
场景
有限状态机
- 有限个状态, 以及在这些状态之间的变化
- 如交通信号灯
- 使用开源 lib: javascript-state-machine
有限状态机- "收藏" 和 "取消"


写一个简单的 Promise
- 实现 Promise
- Promise 三种状态变化: pending fulfilled rejected
- pending -> fulfilled 或者 pending -> rejected
- 不能逆向变化


设计原则验证
- 将状态对象和主体对象分离, 状态的变化逻辑单独处理
- 符合开放封闭原则
网友评论