狀態(tài)模式
允許一個(gè)對(duì)象或者類,在其內(nèi)部狀態(tài)修改時(shí)改變它的行為.
- 圖例
image.png
- 普通代碼示例
class Battery{
constructor(){
this.amount=100
this.state='success'
}
show(){
if(this.amount==100){
console.log('顯示綠色')
this.state='success'
this.amount=60
}else if(this.amount==60){
console.log('顯示黃色')
this.state='warning'
this.amount=30
}else{
console.log('顯示紅色')
this.state='danger'
this.amount=10
}
}
}
let batter=new Battery()
batter.show() //顯示綠色
batter.show()//顯示黃色
batter.show()//顯示紅色
- 狀態(tài)模式優(yōu)化版
//定義單獨(dú)狀態(tài)類,把顯示的邏輯委托給了狀態(tài)對(duì)象驹闰,內(nèi)部還需要維護(hù)狀態(tài)變化.
class SuccessState{
constructor(batter){
this.batter=batter
}
show(){
console.log('顯示綠色')
this.batter.amount=60
return 'success'
}
}
class WarningState{
constructor(batter){
this.batter=batter
}
show(){
console.log('顯示黃色')
this.batter.amount=30
return 'warning'
}
}
class DangerState{
constructor(batter){
this.batter=batter
}
show(){
console.log('顯示紅色')
this.batter.amount=10
return 'danger'
}
}
class Battery{
constructor(){
this.amount=100
this.state=new SuccessState(this)
}
show(){
this.state.show()
if(this.amount==100){
this.state=new SuccessState(this)
}else if(this.amount==60){
this.state=new WarningState(this)
}else{
this.state=new DangerState(this)
}
}
}
let batter=new Battery()
batter.show() //顯示綠色
batter.show()//顯示黃色
batter.show()//顯示紅色
- 使用場(chǎng)景
javascript-state-machine庫(kù)
const StateMachine=require('javascript-state-machine')
var fsm = new StateMachine({
init: 'solid',
transitions: [
{ name: 'melt', from: 'solid', to: 'liquid' },
{ name: 'freeze', from: 'liquid', to: 'solid' },
{ name: 'vaporize', from: 'liquid', to: 'gas' },
{ name: 'condense', from: 'gas', to: 'liquid' }
],
methods: {
onMelt: function() { console.log('I melted')},
onFreeze: function() { console.log('I froze') },
onVaporize: function() { console.log('I vaporized') },
onCondense: function() { console.log('I condensed') }
}
});
fsm.freeze()
優(yōu)點(diǎn) |
---|
1.封裝了轉(zhuǎn)換規(guī)則 |
2.將所有某個(gè)狀態(tài)相關(guān)的行為放到一個(gè)類中,并可以方便的增加新的狀態(tài). |
3.允許狀態(tài)轉(zhuǎn)換邏輯與狀態(tài)對(duì)象合成一體,而不是某一個(gè)巨大的條件語(yǔ)句塊. |
4.可以讓多個(gè)對(duì)象或者類共享一個(gè)狀態(tài)對(duì)象. |