一个对象有状态变化,每次变化都会触发一个逻辑,不能总是用if...else
来控制。比如交通信号红绿灯,收藏,关注,,
举例:
//状态单独抽象出来
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();
let green = new State('green');
let yellow = new State('yellow');
let red = new State('red');
//绿灯亮了,状态的切换和获取是分离的
//状态的切换
green.handle(context);
//状态的获取
var state = context.getState();
console.log(state);
//红灯亮了
red.handle(context);
var state = context.getState();
console.log(state);
//黄灯亮了
yellow.handle(context);
var state = context.getState();
console.log(state);
// turn to green light
// State { color: 'green' }
// turn to red light
// State { color: 'red' }
// turn to yellow light
// State { color: 'yellow' }