EventBus 패턴 구현
This commit is contained in:
parent
5c21b07583
commit
06d3aaf077
8
Assets/_DDD/_Scripts/GameFramework/EventBus.meta
Normal file
8
Assets/_DDD/_Scripts/GameFramework/EventBus.meta
Normal file
@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: d9d81b77c0e15e5459af3bbbacf9c8b3
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
52
Assets/_DDD/_Scripts/GameFramework/EventBus/EventBus.cs
Normal file
52
Assets/_DDD/_Scripts/GameFramework/EventBus/EventBus.cs
Normal 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();
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: e57263a6fcda2cb43a03e0b4efd4848e
|
7
Assets/_DDD/_Scripts/GameFramework/EventBus/IEvent.cs
Normal file
7
Assets/_DDD/_Scripts/GameFramework/EventBus/IEvent.cs
Normal file
@ -0,0 +1,7 @@
|
||||
namespace DDD
|
||||
{
|
||||
public interface IEvent
|
||||
{
|
||||
|
||||
}
|
||||
}
|
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: ffb2216f8e1a979449b7fb4caa575033
|
@ -0,0 +1,7 @@
|
||||
namespace DDD
|
||||
{
|
||||
public interface IEventHandler<in T> where T : IEvent
|
||||
{
|
||||
void Handle(T evt);
|
||||
}
|
||||
}
|
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 0dd9940e2db491b4fae6d77773427b36
|
Loading…
Reference in New Issue
Block a user