2015-12-10 15 views
0

我在想我可以使用的模式。根据给定状态委托调用的模式

我希望能够有一个中间人模块需要在一种游戏的状态。鉴于该状态,请调用驻留在anotehr模块中的某个方法。

我可以用什么模式来呢?

例如,我希望能够采取的“计算机总是赢”,并基于该状态的类型,我会打电话给someOtherModule.makeComputerMove()的状态。在未来,也许我们希望能够将游戏设置为电脑不总是赢的模式。那好吧,我们可以在"normal game"状态或类似的东西它只是调用computerAlwaysWins.makeComputerMove()从为normalGame.makeComputerMove()

的想法不同的使用情况模块,例如送?

我想不出任何方式来提供这样的事......可能是因为我不知道他们中的很多。

+0

状态模式听起来不错吗? Google是你的朋友。 – skypjack

回答

0

你应该观察的组合可能使用状态模式。

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); 
    } 
} 

我希望你抓住一个主意,祝你好运!