using System; using System.Collections.Generic; using System.Linq; namespace 电子展板.Utility { public class EventBus { private static object _lock = new object(); private List list; private List strlist; /// /// 单例,防止实例化 /// private EventBus() { list = new List(); strlist = new List(); } private static EventBus _instance; /// /// 获取实例 /// public static EventBus Instance { get { if (_instance == null) { _instance = new EventBus(); return _instance; } return _instance; } } /// /// 订阅消息,obj这个对象订阅T这个消息,发布消息时调用回调方法 /// /// /// /// public void Subscribe(object obj, Action callBackFunc) where T : IEvent { try { //判断有没有注册过,注册过就不能再注册。疑惑点,一个类中多次注册行不行?? if (list.Any(it => it.Subscriber == obj && it.EventType == typeof(T))) { return; } list.Add(new CallBacks { Subscriber = obj, EventType = typeof(T), Action = new Action(o => callBackFunc((T)o)) }); } catch (Exception ex) { } } /// /// 取消订阅,obj这个对象取消订阅T这个消息 /// /// /// public void UnSubscribe(object obj) where T : IEvent { try { list.RemoveAll(it => it.Subscriber == obj && it.EventType == typeof(T)); } catch (Exception ex) { } } /// /// 发布消息 /// /// /// public void Publish(T data) where T : IEvent { list.Where(it => it.EventType == typeof(T)).ToList().ForEach(it => { //Task.Run(() => it.Action(data)); try { it.Action(data); } catch (Exception ex) { } }); } public void Subscribe(object obj, string eventName, Action callBackFunc) { try { //判断有没有注册过,注册过就不能再注册。疑惑点,一个类中多次注册行不行?? if (strlist.Any(it => it.Subscriber == obj && it.EventName == eventName)) { return; } strlist.Add(new StrCallBacks { Subscriber = obj, EventName = eventName, Action = callBackFunc }); } catch (Exception ex) { } } public void UnSubscribe(object obj, string eventName) { try { strlist.RemoveAll(it => it.Subscriber == obj && it.EventName == eventName); } catch (Exception ex) { } } public void Publish(string eventName, string data) { try { strlist.Where(it => it.EventName == eventName).ToList().ForEach(it => { it.Action(data); }); } catch (Exception ex) { } } /// /// 内部类 /// class CallBacks { /// /// T的类型 /// public Type EventType { get; set; } /// /// 谁订阅对象 /// public object Subscriber { get; set; } public Action Action { get; set; } } class StrCallBacks { /// /// T的类型 /// public string EventName { get; set; } /// /// 谁订阅对象 /// public object Subscriber { get; set; } public Action Action { get; set; } } } public interface IEvent { } public class ConsoleLogEvent : IEvent { public DateTime DateTime { get; set; } public string Message { get; set; } public string Type { get; set; } public ConsoleLogEvent(string message) : this("I", message) { } public ConsoleLogEvent(string type, string message) { this.Type = type; this.Message = message; this.DateTime = DateTime.Now; } public override string ToString() { return $"{DateTime.ToString("yyyy-MM-dd HH:mm:ss.fff")}[{Type}]->{Message}"; } } public class ClearLogEvent : IEvent { } }