状态模式全解析--JavaScript

Posted 白马非马

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了状态模式全解析--JavaScript相关的知识,希望对你有一定的参考价值。

1 初级电灯例子 , 状态仅仅用字符串表示,没有封装到对象

class Light{
    constructor(){
        this.state = off;
        let button = document.createElement( button );
        button.innerhtml = 开关;
        this.button = document.body.appendChild( button );
        this.button.onclick = ()=>{
            this.buttonWasPressed();
        }
    }
    buttonWasPressed(){
        if ( this.state === off ){
            console.log( 开灯 );
            this.state = on;
        }else if ( this.state === on ){
            console.log( 关灯 );
            this.state = off;
        }
    }

}
new Light();

//  状态模式----面向对象版本

  实现的关键

  1 状态用对象表示

  2 状态对应的行为 抽象成一个统一的方法(buttonWasPressed),可以实现委托。这个行为可以放到状态类里,也可以放到context里,

  3 状态内部 会自己修改当前的状态,(也就是下一个状态是什么,在每一个状态对象内部已经明确,)

  4 当触发操作开始时,会用当前状态调用当前状态对应的行为,从而成功避免了使用丑陋的if else 分支,

 1 class State{
 2     buttonWasPressed(){
 3         throw new Error( ‘父类的 buttonWasPressed 方法必须被重写‘ )
 4     }
 5 }
 6 
 7 class StrongLightState extends State{
 8     constructor(light){
 9         super();
10         this.light = light
11     }
12     // buttonWasPressed(){
13     //     console.log(‘-->关灯‘);
14     //     this.light.setState(this.light.offLightState)
15     // }
16 }
17 
18 class OffLightState  extends State{
19     constructor(light){
20         super();
21         this.light = light
22     }
23     buttonWasPressed(){
24         console.log(‘-->弱光‘);
25         this.light.setState(this.light.weakLightState)
26     }
27 }
28 
29 class WeakLightState  extends State{
30     constructor(light){
31         super();
32         this.light = light
33     }
34     buttonWasPressed(){
35         console.log(‘-->强光‘);
36         this.light.setState(this.light.strongLightState)
37     }
38 }
39 
40 class  Light{
41     constructor(){
42         this.strongLightState = new StrongLightState(this);
43         this.offLightState = new OffLightState(this);
44         this.weakLightState = new WeakLightState(this);
45         this.currState = this.offLightState; // 设置当前状态
46 
47         let button = document.createElement( ‘button‘ );
48         button.innerHTML = ‘开关‘;
49         this.button = document.body.appendChild( button );
50         this.button.onclick = ()=>{
51             this.currState.buttonWasPressed();
52         }
53     }
54 
55     setState(newState){
56         this.currState = newState
57     }
58 }

 

以上是关于状态模式全解析--JavaScript的主要内容,如果未能解决你的问题,请参考以下文章

23种设计模式全解析

尝试使用片段保存夜间模式状态

JavaScript状态模式及状态机模型

仅在一个片段中隐藏状态栏并在其他片段中显示

2018TPC必火,全解析

JavaScript全解析——this指向