0

当全局游戏状态发生变化时,如何在所有派生类中调用函数?

public abstract class GameStateBehaviour {

    public event EventHandler<GameStateEvents> StateChanged;

    protected virtual void OnStateChanged(GameStateEvents e) {
        // Call this function in all derived
    }

}
4

2 回答 2

1

如果您想通知其他类有关状态更改,我们使用“观察者模式”(参见:http ://en.wikipedia.org/wiki/Observer_pattern )。有两个政党:

  • 一方是“对象”,它将改变状态。他有义务通知其他人。
  • 对方是“观察者”。多个观察者想要观察对象的状态变化。所以他们想被告知。

尝试这个:

class TheObject
{
    public event EventHandler<GameStateEvents> StateChanged;

    // If your object changes state, this function should be called. It informs all observers by invoking the StateChanged delegate.
    protected virtual void OnStateChanged(GameStateEvents e)
    {
        if (StateChanged != null) 
            StateChanged(this, e);
    }
}

class TheObserver
{
     public TheObserver(TheObject o)
     {
         o.StateChanged += Object_StateChanged;
     }

     // This function is called by the object when the object changes state.
     private void Object_StateChanged(object sender, GameStateEvents e)
     {
     }
}
于 2013-05-10T10:07:49.223 回答
0

OnStateChanged方法是应该触发StateChanged事件的方法。不是将处理此事件的方法。这就是我添加该FunctionCalledWhenStateChanges方法的原因。

public abstract class GameStateBehaviour
{
    public event EventHandler<GameStateEvents> StateChanged;

    protected GameStateBehaviour()
    {
        StateChanged += (sender, events) => FunctionCalledWhenStateChanges();
    }

    public virtual void FunctionCalledWhenStateChanges()
    {
        // The called function
    }

    protected void OnStateChanged(GameStateEvents e)
    {
        if (StateChanged != null) StateChanged(this, e);
    }
}

上面的解决方案处理您自己的事件。我认为最好实现模板方法模式而不是响应您自己的事件。但是我认为您不确定在哪里举办活动。

于 2013-05-10T10:03:01.613 回答