EventBus.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. using OOO_WriteAndClear.EventBus.Signals;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. namespace OOO_WriteAndClear.EventBus
  8. {
  9. public class EventBus
  10. {
  11. private static EventBus? _bus = null;
  12. protected EventBus()
  13. {
  14. _allSubscribers = new Dictionary<string, LinkedList<object>>();
  15. }
  16. public static EventBus GetService()
  17. {
  18. if (_bus is null)
  19. return _bus = new EventBus();
  20. return _bus;
  21. }
  22. public void Subscribe<T>(Action<T> signal) where T : ISignal
  23. {
  24. string? signalName = typeof(T).FullName;
  25. if (signalName is null)
  26. throw new NotSupportedException();
  27. if(_allSubscribers.ContainsKey(signalName))
  28. {
  29. _allSubscribers[signalName].AddLast(signal);
  30. return;
  31. }
  32. LinkedList<object> newSubscribers = new LinkedList<object>();
  33. newSubscribers.AddFirst(signal);
  34. _allSubscribers.Add(signalName, newSubscribers);
  35. }
  36. public void Unsubscribe<T>(Action<T> signal) where T : ISignal
  37. {
  38. string? signalName = typeof(T).FullName;
  39. if (signalName is null)
  40. throw new NotSupportedException();
  41. if (!_allSubscribers.ContainsKey(signalName))
  42. return;
  43. _allSubscribers[signalName].Remove(signal);
  44. }
  45. public void Invoke<T>(T signal) where T : ISignal
  46. {
  47. string? signalName = signal.GetType().FullName;
  48. if (signalName is null)
  49. throw new NotSupportedException();
  50. if (!_allSubscribers.ContainsKey(signalName))
  51. return;
  52. foreach(var action in _allSubscribers[signalName])
  53. ((Action<T>)action)?.Invoke(signal);
  54. }
  55. private Dictionary<string, LinkedList<object>> _allSubscribers;
  56. }
  57. }