52 lines
1.4 KiB
C#
52 lines
1.4 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
|
|
namespace DDD
|
|
{
|
|
public static class EventBus
|
|
{
|
|
private static readonly Dictionary<Type, List<object>> HandlerDictionary = new();
|
|
|
|
public static void Register<T>(IEventHandler<T> handler) where T : IEvent
|
|
{
|
|
var type = typeof(T);
|
|
if (!HandlerDictionary.ContainsKey(type))
|
|
{
|
|
HandlerDictionary[type] = new List<object>();
|
|
}
|
|
|
|
HandlerDictionary[type].Add(handler);
|
|
}
|
|
|
|
public static void Unregister<T>(IEventHandler<T> handler) where T : IEvent
|
|
{
|
|
var type = typeof(T);
|
|
if (HandlerDictionary.TryGetValue(type, out var list))
|
|
{
|
|
list.Remove(handler);
|
|
if (list.Count == 0)
|
|
{
|
|
HandlerDictionary.Remove(type);
|
|
}
|
|
}
|
|
}
|
|
|
|
public static void Broadcast<T>(T evt) where T : IEvent
|
|
{
|
|
var type = typeof(T);
|
|
if (HandlerDictionary.TryGetValue(type, out var list))
|
|
{
|
|
foreach (var handler in list.Cast<IEventHandler<T>>())
|
|
{
|
|
handler.Invoke(evt);
|
|
}
|
|
}
|
|
}
|
|
|
|
public static void ClearAll()
|
|
{
|
|
HandlerDictionary.Clear();
|
|
}
|
|
}
|
|
} |