JavaScript中的设计模式:状态模式

前几天写了一个贪吃蛇小游戏,正好用到了状态模式。

定义

当一个对象内部状态发生改变时候,会导致其行为的改变,这看起来像是改变了对象。

简单的例子

如果一个函数要更具某一个对象的状态来判断该对象应该执行的方法,那么这个函数中会增加很多if判断分支,并且,如果要增加这个对象的一种状态,那么就要在原来的代码中添加一些判断,比较麻烦。例如,贪吃蛇有移动、吃食物、死亡等状态,如果我在处理这些状态的时候这么写代码(如下面)

this.process = function(point){
        if (this.ifDie(point)) {
            this.energy.stopGame();
            return;
        }
               //eating
        if (this.eatable(point)) {
            this.energy.removePoint(point);
            this.addPoint(point);//添加节点
            this.manager.addScore();
            this.productFood();
        }
               //moving
        else {
            this.addPoint(point);
            this.delTail();//删除尾部界面
        }

 这里更具point来判断是什么状态,然后用游戏引擎渲染这个画面,如果在给蛇增加一种休息的状态,那么代码中就要增加if判断了,所以修改后的代码是这样的

self.state = {
        die:function(){
            self.energy.stop();
        },
        eatable:function(point){
            self.energy.removeFood(point);
            self.addPoint(point);
            self.energy.addScore();
            self.productFood();
        },
        moving:function(point){
            self.addPoint(point);
            self.delTail();
        }
    };//蛇的状态
    self.currentState = null;
Snake.prototype.process = function(currentState,point){
    this.state[currentState](point);
}

完整的代码在https://github.com/YAMAPM/greedySnake.

状态模式有点像策略模式,都是根据不同的传递参数实现不同的功能

原文地址:https://www.cnblogs.com/bdbk/p/5297919.html