状态模式(State Pattern)
| 1 2 3 | 定义:创建表示各种状态的对象和一个行为随着状态对象改变而改变的 context 对象。 目的:允许对象在内部状态发生改变时改变它的行为,对象看起来好像修改了它的类。 场景:游戏角色有跳跃、移动、射击、蹲下等状态设定,如果用if-else或者switch来进行判断,在遇到组合动作的时候,判断会变得非常复杂难读,这时可以使用状态模式来实现。 | 
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | 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() | 

