標籤: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