我试图为游戏实现一个事件系统,其中有一些类可以触发或处理事件,无论它们是否实现这些接口:
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;
}
}
按键事件:
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));
}
}
手动将用户存储在EventSystem的列表中会更好吗?
这将比这种方法慢或快多少?
谢谢!
常见的方法是实现事件聚合器模式。谷歌搜索将为您提供大量不同的变体。例如,它可能看起来像这样(我目前正在使用的):
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);
}