我正在尝试为游戏实现一个事件系统,其中有些类可以触发或处理事件,而不是它们实现这些接口:
public interface IGameEvent<T> where T : EventArgs
{
event EventHandler<T> OnEvent;
}
public interface IGameHandler<T> where T : EventArgs
{
void OnEvent(object sender, T e);
}
一切看起来都很棒,直到我意识到没有一个类可以实现超过1个IGameEvent 因为它会导致重复声明,
以下是一个例子:
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));
}
}
最好将Suscribers手动存储在EventSystem的列表中?
比这种方法更慢或更快?
谢谢!
答案 0 :(得分:1)
常见的方法是实现事件聚合器模式。 Google搜索将为您提供大量不同的变体。例如,它可能看起来像这样(我目前使用的是):
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);
}