基于给定状态委托呼叫的模式

时间:2015-12-10 07:20:31

标签: javascript node.js design-patterns

我试图想出一个我可以使用的模式。

我希望能够拥有一个兼顾游戏状态的中间人模块。给定该状态,调用驻留在anotehr模块中的某种方法。

我可以使用哪种模式?

例如,我希望能够进入"计算机永远胜利"并根据该州的类型,我会拨打someOtherModule.makeComputerMove()。在未来,我们希望能够将游戏设置为计算机并不总能获胜的模式。那么我们可以发送"normal game"或类似的状态,只能从computerAlwaysWins.makeComputerMove()

等不同的用例模块调用normalGame.makeComputerMove()

明白了吗?

我无法想到提供这样的事情的任何模式......可能是因为我不太了解它们。

1 个答案:

答案 0 :(得分:0)

你应该使用状态模式与Observer的组合。

public class GameStateContext {
    PlayerState Player {get;set; }
    // other properties that need to be shared
}

public interface IGameController {
    void GoToState(State state)
}

public interface IGameState {
   void Start();
   void Update();
}

public abstract class GameStateBase : IGameState {
    protected GameStateContext _context;
    protected IGameController _parent;

    public GameStateBase(GameStateContext context, IGameController parent) {
        this._context = context;
        this._parent = parent;    
    }

    public virtual void Start() {

    }

    public virtual void Update() {

    }
}

public class BonusLevelState : GameStateBase {
   public public MainMenuState (GameStateContext context, IGameController parent) : base (context, parent) {

   }

   public override void Update() {
       if(_context.Player.Health == 0) {
           _parent.GoToState(GameStates.GameOver);
       }
   }
}

public GameController : IGameController {
    public enum GameStates {
        BonusLevel,
        InitialState,
        ....
    }

    private IGameState currentState;

    public GameController() {
        // create diferent states
        ...
        currentState = GetState(GameStates.InitialState);
    }

    public void Update {
       currentState.Update();
    }

    public GoToState(State state) {
        currentState = GetState(state);
    }
}

我希望你能抓住一个想法,祝​​你好运!