状态模式(State Pattern)
定义:创建表示各种状态的对象和一个行为随着状态对象改变而改变的 context 对象。
目的:允许对象在内部状态发生改变时改变它的行为,对象看起来好像修改了它的类。
场景:游戏角色有跳跃、移动、射击、蹲下等状态设定,如果用if-else或者switch来进行判断,在遇到组合动作的时候,判断会变得非常复杂难读,这时可以使用状态模式来实现。
class SuperHero {
constructor () {
this.currentState = []
this.states = {
jump () {
console.log('jump')
},
move () {
console.log('move')
},
shoot () {
console.log('shoot')
},
squat () {
console.log('squat')
}
}
}
// 更改当前状态
change (arr) {
this.currentState = arr
return this
}
run () {
console.log('..... begin start ......')
this.currentState.forEach(item => this.states[item] && this.states[item]())
return this
}
}
new SuperHero()
.change(['jump', 'squat'])
.run()
.change(['move', 'shoot'])
.run()
Github地址:github.com/skillnull/D…