namespace Guru
{
using System;
using System.Collections.Generic;
///
/// 事件管线基类
///
public class EventBus
{
private Dictionary> _eventDict;
protected Dictionary> EventDict
{
get
{
if (_eventDict == null)
{
_eventDict = new Dictionary>(20);
}
return _eventDict;
}
}
///
/// 发送事件
///
///
///
///
public bool Send(T eventBody) where T : struct
{
return Trigger(eventBody);
}
///
/// 订阅消息
///
///
///
public void Subscribe(Action onReceiveMessage) where T : struct
{
AddListener(onReceiveMessage);
}
public void Unsubscribe(Action onReceiveMessage) where T : struct
{
RemoveListener(onReceiveMessage);
}
public void Dispose()
{
if (_eventDict != null)
{
foreach (var actions in _eventDict.Values)
{
actions.Clear();
}
_eventDict.Clear();
}
}
protected bool HasEvent() where T : struct
{
return EventDict.ContainsKey(nameof(T));
}
protected void AddListener(Action onReceiveMessage) where T : struct
{
if (!HasEvent())
{
EventDict[nameof(T)] = new HashSet();
}
EventDict[nameof(T)].Add(onReceiveMessage);
}
protected void RemoveListener(Action onReceiveMessage) where T : struct
{
if (HasEvent())
{
if (EventDict[nameof(T)].Contains(onReceiveMessage))
{
EventDict[nameof(T)].Remove(onReceiveMessage);
}
}
}
///
///
///
///
///
///
protected bool Trigger(T message) where T : struct
{
if (HasEvent())
{
HashSet newActions = new HashSet(EventDict[nameof(T)].Count);
foreach (var d in EventDict[nameof(T)])
{
if (d.Target != null)
{
(d as Action)?.Invoke(message);
newActions.Add(d);
}
}
EventDict[nameof(T)] = newActions; // 过滤掉不存在的时间
return true;
}
return false;
}
}
}