JavaScript设计模式样例十五 —— 状态模式

状态模式(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()

Git地址:https://github.com/skillnull/Design-Mode-Example

原文地址:https://www.cnblogs.com/Man-Dream-Necessary/p/12516434.html