using OOO_WriteAndClear.EventBus.Signals; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OOO_WriteAndClear.EventBus { public class EventBus { private static EventBus? _bus = null; protected EventBus() { _allSubscribers = new Dictionary>(); } public static EventBus GetService() { if (_bus is null) return _bus = new EventBus(); return _bus; } public void Subscribe(Action signal) where T : ISignal { string? signalName = typeof(T).FullName; if (signalName is null) throw new NotSupportedException(); if(_allSubscribers.ContainsKey(signalName)) { _allSubscribers[signalName].AddLast(signal); return; } LinkedList newSubscribers = new LinkedList(); newSubscribers.AddFirst(signal); _allSubscribers.Add(signalName, newSubscribers); } public void Unsubscribe(Action signal) where T : ISignal { string? signalName = typeof(T).FullName; if (signalName is null) throw new NotSupportedException(); if (!_allSubscribers.ContainsKey(signalName)) return; _allSubscribers[signalName].Remove(signal); } public void Invoke(T signal) where T : ISignal { string? signalName = signal.GetType().FullName; if (signalName is null) throw new NotSupportedException(); if (!_allSubscribers.ContainsKey(signalName)) return; foreach(var action in _allSubscribers[signalName]) ((Action)action)?.Invoke(signal); } private Dictionary> _allSubscribers; } }