基于给定状态的委派调用模式

Pattern for Delegating Calls based on A Given State

本文关键字:委派 调用 模式 状态      更新时间:2023-09-26

我正在想一个可以使用的模式。

我希望能够有一个中间人模块,采取一种游戏的状态。给定该状态,调用另一个模块中的某个方法。

我可以用什么图案做这个?

例如,我希望能够接受"计算机总是获胜"的状态,并根据该状态类型,我将调用someOtherModule.makeComputerMove()。在未来,也许我们希望能够将游戏设置为计算机并不总是获胜的模式。那么我们可以发送"normal game"或类似的状态,它只会从不同的用例模块(如normalGame.makeComputerMove() )调用computerAlwaysWins.makeComputerMove()

明白了吗?

我想不出任何模式来提供这样的东西。。。可能是因为我不太了解他们。

您应该将State模式与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);
    }
}

我希望你有个主意,祝你好运!