前幾天寫了一個貪吃蛇小游戲,正好用到了狀態模式。
當一個對象內部狀態發生改變時候,會導致其行為的改變,這看起來像是改變了對象。
如果一個函數要更具某一個對象的狀態來判斷該對象應該執行的方法,那麼這個函數中會增加很多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.
狀態模式有點像策略模式,都是根據不同的傳遞參數實現不同的功能