(JS)状态模式
每次状态变化都会触发逻辑
不能总是使用if…else判断
class State {
constructor(color) {
this.color = color;
}
handle() {
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();
let green = new State("green");
let red = new State("red");
let yellow = new State("yellow");
green.handle();
red.handle();
yellow.handle();
console.log(context.getState());
turn to green light
turn to red light
turn to yellow light
State {color: "yellow"}