状态模式
允许一个对象或者类,在其内部状态修改时改变它的行为.
- 图例

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()//显示红色
- 状态模式优化版
//定义单独状态类,把显示的逻辑委托给了状态对象,内部还需要维护状态变化.
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()//显示红色
- 使用场景
javascript-state-machine库
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()
| 优点 |
|---|
| 1.封装了转换规则 |
| 2.将所有某个状态相关的行为放到一个类中,并可以方便的增加新的状态. |
| 3.允许状态转换逻辑与状态对象合成一体,而不是某一个巨大的条件语句块. |
| 4.可以让多个对象或者类共享一个状态对象. |