EventBus 패턴 구현

This commit is contained in:
NTG_Lenovo 2025-07-16 18:21:12 +09:00
parent 5c21b07583
commit 06d3aaf077
7 changed files with 80 additions and 0 deletions

View File

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: d9d81b77c0e15e5459af3bbbacf9c8b3
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,52 @@
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();
}
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: e57263a6fcda2cb43a03e0b4efd4848e

View File

@ -0,0 +1,7 @@
namespace DDD
{
public interface IEvent
{
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: ffb2216f8e1a979449b7fb4caa575033

View File

@ -0,0 +1,7 @@
namespace DDD
{
public interface IEventHandler<in T> where T : IEvent
{
void Handle(T evt);
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 0dd9940e2db491b4fae6d77773427b36