using System; using System.Collections.Generic; namespace EGFramework { public interface IEGEvent{ void SendEvent() where T : new(); void SendEvent(T e); IUnRegister RegisterEvent(Action onEvent); void UnRegisterEvent(Action onEvent); } public class EGEvent : EGModule,IEGEvent { public override void Init() { } private readonly EasyEvents Events = new EasyEvents(); public void SendEvent() where TEvent : new() { Events.GetEvent>()?.Invoke(new TEvent()); } public void SendEvent(TEvent e) { Events.GetEvent>()?.Invoke(e); } public IUnRegister RegisterEvent(Action onEvent) { var e = Events.GetOrAddEvent>(); return e.Register(onEvent); } public void UnRegisterEvent(Action onEvent) { var e = Events.GetEvent>(); if (e != null) { e.UnRegister(onEvent); } } } public class EasyEvents { private static EasyEvents GlobalEvents = new EasyEvents(); public static T Get() where T : IEasyEvent { return GlobalEvents.GetEvent(); } public static void Register() where T : IEasyEvent, new() { GlobalEvents.AddEvent(); } private Dictionary TypeEvents = new Dictionary(); public void AddEvent() where T : IEasyEvent, new() { TypeEvents.Add(typeof(T), new T()); } public T GetEvent() where T : IEasyEvent { IEasyEvent e; if (TypeEvents.TryGetValue(typeof(T), out e)) { return (T)e; } return default; } public T GetOrAddEvent() where T : IEasyEvent, new() { var eType = typeof(T); if (TypeEvents.TryGetValue(eType, out var e)) { return (T)e; } var t = new T(); TypeEvents.Add(eType, t); return t; } } public static class CanRegisterEventExtension { public static IUnRegister EGRegisterEvent(this IEGFramework self, Action onEvent) { return EGArchitectureImplement.Interface.GetModule().RegisterEvent(onEvent); } public static void EGUnRegisterEvent(this IEGFramework self, Action onEvent) { EGArchitectureImplement.Interface.GetModule().UnRegisterEvent(onEvent); } } public static class CanSendEventExtension { public static void EGSendEvent(this IEGFramework self) where T : new() { EGArchitectureImplement.Interface.GetModule().SendEvent(); } public static void EGSendEvent(this IEGFramework self, T e) { EGArchitectureImplement.Interface.GetModule().SendEvent(e); } } }