1

Im trying to implement an Event System for a game, where there are classes that can fire or handle an event wheter or not they implement these interfaces:

public interface IGameEvent<T> where T : EventArgs
{
     event EventHandler<T> OnEvent;
}

public interface IGameHandler<T> where T : EventArgs
{
    void OnEvent(object sender, T e);
}

everything looked great until i realized that no class can implement more than 1 IGameEvent because it would cause duplicate declaration,

Here is an example:

public class Event
{
    public KeyPressEvent OnKeyPress;
    public UpdateEvent OnUpdate;

    public void AddHadler<T>(IGameEvent<T> eEvent , IGameHandler<T> eHandler) where  T : EventArgs
    {
        eEvent.OnEvent += eHandler.OnEvent;
    }

    public void RemoveHandler<T>(IGameEvent<T> eEvent, IGameHandler<T> eHandler) where T : EventArgs
    {
        eEvent.OnEvent -= eHandler.OnEvent;
    }
}

KeyPressEvent:

public class KeyPressEvent : IGameEvent<KeyPressEvent.KeyPressedEventArgs>
{
    public class KeyPressedEventArgs : EventArgs
    {
        public KeyPressedEventArgs(Keys key)
        {
            Key = key;
        }

        public Keys Key { get; private set; }
    }

    public event EventHandler<KeyPressedEventArgs> OnEvent;

    private void OnCheckForKeyPressed()  //Example
    {
        if (OnEvent != null) 
            OnEvent(this, new KeyPressedEventArgs(Keys.Space));
    }
}

Would be better to manually store the suscribers in a list in the EventSystem ?

How slower or faster than this approach that would be?

Thanks!

4

1 回答 1

1

常见的方法是实现事件聚合器模式。谷歌搜索将为您提供大量不同的变体。例如,它可能看起来像这样(我目前使用的):

interface IEventsAggrgator
{
    //fires an event, reperesented by specific message
    void Publish<TMessage>(TMessage message);
    //adds object to the list of subscribers
    void Subscribe(object listener);
    //remove object from the list of subscribers
    void Unsubscribe(object listener);
}

interface IHandler<TMessage>
{
    //implement this in subscribers to handle specific messages
    void Handle(TMessage message);
}
于 2013-07-29T05:45:14.780 回答