
说明
1、关键是区分事物内部的状态,事物内部状态往往会带来事物的行为改变。
即允许对象在内部状态发生改变时改变它的行为。
2、状态模式就是封装状态,允许一个对象在其内部状态改变时改变它的行为,我们之前一般都是封装行为。
实例
//红灯
classRedLight{
constructor(state){
this.state=state;
}
light(){
console.log('turntoredlight');
this.state.setState(this.state.greenLight)
}
}
//绿灯
classgreenLight{
constructor(state){
this.state=state;
}
light(){
console.log('turntogreenlight');
this.state.setState(this.state.yellowLight)
}
}
//黄灯
classyellowLight{
constructor(state){
this.state=state;
}
light(){
console.log('turntoyellowlight');
this.state.setState(this.state.redLight)
}
}
classState{
constructor(){
this.redLight=newRedLight(this)
this.greenLight=newgreenLight(this)
this.yellowLight=newyellowLight(this)
this.setState(this.redLight)//初始化为红灯
}
setState(state){
this.currState=state;
}
}
conststate=newState();
state.currState.light()//turntoredlight
setInterval(()=>{
state.currState.light()//每隔3秒依次打印红灯、绿灯、黄灯
},3000)
以上就是js状态模式的介绍,希望对大家有所帮助。更多js学习指路:js教程
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END
    


















































暂无评论内容