123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566 |
- 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<string, LinkedList<object>>();
- }
- public static EventBus GetService()
- {
- if (_bus is null)
- return _bus = new EventBus();
- return _bus;
- }
- public void Subscribe<T>(Action<T> 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<object> newSubscribers = new LinkedList<object>();
- newSubscribers.AddFirst(signal);
- _allSubscribers.Add(signalName, newSubscribers);
- }
- public void Unsubscribe<T>(Action<T> 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>(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<T>)action)?.Invoke(signal);
- }
- private Dictionary<string, LinkedList<object>> _allSubscribers;
- }
- }
|