狀態模式全解析--JavaScript

來源:互聯網
上載者:User

標籤:java   style   cto   使用   開始   htm   --   else   tor   

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 = light11     }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 = light22     }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 = light33     }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 = newState57     }58 }

 

狀態模式全解析--JavaScript

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.