using System.Collections.Generic; using System; public class MessageCenter { private static MessageCenter instance; public static MessageCenter Instance { get { if (instance == null) instance = new MessageCenter();return instance; } } Action<object> action; private static Dictionary<string, List<Action<object>>> dic = new Dictionary<string, List<Action<object>>>(); /// <summary> /// 增加监听 /// </summary> /// <param name="str"></param> /// <param name="action"></param> public static void AddListener(string str,Action<object> action) { if(dic.ContainsKey(str)) { dic[str].Add(action); } else { List<Action<object>> list = new List<Action<object>>(); list.Add(action); dic.Add(str, list); } } /// <summary> /// 移除一个监听 /// </summary> /// <param name="str"></param> public static void RemoveListener(string str) { if(!dic.ContainsKey(str)) { return; } for(int i=0;i<dic[str].Count;i++) { dic[str].Clear(); } } /// <summary> /// 发送消息 /// </summary> /// <param name="str"></param> /// <param name="obj"></param> public static void SendMessage(string str,object obj) { if(dic.ContainsKey(str)) { for(int i=0;i<dic[str].Count;i++) { dic[str][i](obj); } } } /// <summary> /// 清空监听 /// </summary> public static void Clear() { dic.Clear(); } }