ProjectDDD/Assets/_DDD/_Scripts/GameFramework/EventBus/EventBus.cs
2025-07-16 18:21:12 +09:00

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 Publish<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.Handle(evt);
}
}
}
public static void ClearAll()
{
HandlerDictionary.Clear();
}
}
}