EventNotificationCenter.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. // #define LOG_ALL_MESSAGES
  2. //#define LOG_ADD_LISTENER
  3. //#define LOG_BROADCAST_MESSAGE
  4. //#define REQUIRE_LISTENER
  5. using UnityEngine;
  6. using System.Collections;
  7. using System.Collections.Generic;
  8. using System;
  9. public class EventNotificationCenter
  10. {
  11. public Dictionary<string, Delegate> eventTable = new Dictionary<string, Delegate>();
  12. // Message handlers that should never be removed, regardless of calling Cleanup
  13. private List< string > permanentMessages = new List< string > ();
  14. public delegate void Callback();
  15. public delegate void Callback<T>(T arg1);
  16. public delegate void Callback<T, U>(T arg1, U arg2);
  17. public delegate void Callback<T, U, V>(T arg1, U arg2, V arg3);
  18. private static EventNotificationCenter instance;
  19. public static EventNotificationCenter GetInstance()
  20. {
  21. if(null == instance)
  22. instance = new EventNotificationCenter();
  23. return instance;
  24. }
  25. EventNotificationCenter()
  26. {
  27. eventTable.Clear();
  28. permanentMessages.Clear();
  29. }
  30. //Marks a certain message as permanent.
  31. public void MarkAsPermanent(string eventType)
  32. {
  33. #if LOG_ALL_MESSAGES
  34. Debug.Log("Messenger MarkAsPermanent \t\"" + eventType + "\"");
  35. #endif
  36. permanentMessages.Add( eventType );
  37. }
  38. public void Cleanup()
  39. {
  40. #if LOG_ALL_MESSAGES
  41. Debug.Log("MESSENGER Cleanup. Make sure that none of necessary listeners are removed.");
  42. #endif
  43. List< string > messagesToRemove = new List<string>();
  44. foreach (KeyValuePair<string, Delegate> pair in eventTable)
  45. {
  46. bool wasFound = false;
  47. foreach (string message in permanentMessages)
  48. {
  49. if (pair.Key == message)
  50. {
  51. wasFound = true;
  52. break;
  53. }
  54. }
  55. if (!wasFound)
  56. messagesToRemove.Add( pair.Key );
  57. }
  58. foreach (string message in messagesToRemove)
  59. {
  60. eventTable.Remove( message );
  61. }
  62. }
  63. public void PrintEventTable()
  64. {
  65. Debug.Log("\t\t\t=== MESSENGER PrintEventTable ===");
  66. foreach (KeyValuePair<string, Delegate> pair in eventTable)
  67. {
  68. Debug.Log("\t\t\t" + pair.Key + "\t\t" + pair.Value);
  69. }
  70. Debug.Log("\n");
  71. }
  72. // -- 1. 事件防御处理
  73. private void OnListenerAdding(string eventType, Delegate listenerBeingAdded)
  74. {
  75. #if LOG_ALL_MESSAGES || LOG_ADD_LISTENER
  76. Debug.Log("MESSENGER OnListenerAdding \t\"" + eventType + "\"\t{" + listenerBeingAdded.Target + " -> " + listenerBeingAdded.Method + "}");
  77. #endif
  78. if (!eventTable.ContainsKey(eventType))
  79. {
  80. eventTable.Add(eventType, null );
  81. }
  82. Delegate d = eventTable[eventType];
  83. if (d != null && d.GetType() != listenerBeingAdded.GetType())
  84. {
  85. throw new ListenerException(string.Format("Attempting to add listener with inconsistent signature for event type {0}. Current listeners have type {1} and listener being added has type {2}", eventType, d.GetType().Name, listenerBeingAdded.GetType().Name));
  86. }
  87. }
  88. private void OnListenerRemoving(string eventType, Delegate listenerBeingRemoved)
  89. {
  90. #if LOG_ALL_MESSAGES
  91. Debug.Log("MESSENGER OnListenerRemoving \t\"" + eventType + "\"\t{" + listenerBeingRemoved.Target + " -> " + listenerBeingRemoved.Method + "}");
  92. #endif
  93. if (eventTable.ContainsKey(eventType))
  94. {
  95. Delegate d = eventTable[eventType];
  96. if (d == null)
  97. {
  98. throw new ListenerException(string.Format("Attempting to remove listener with for event type \"{0}\" but current listener is null.", eventType));
  99. }
  100. else if (d.GetType() != listenerBeingRemoved.GetType())
  101. {
  102. throw new ListenerException(string.Format("Attempting to remove listener with inconsistent signature for event type {0}. Current listeners have type {1} and listener being removed has type {2}", eventType, d.GetType().Name, listenerBeingRemoved.GetType().Name));
  103. }
  104. }
  105. else
  106. {
  107. YmDebug.LogCR(string.Format("Attempting to remove listener for type \"{0}\" but Messenger doesn't know about this event type.", eventType));
  108. //throw new ListenerException(string.Format("Attempting to remove listener for type \"{0}\" but Messenger doesn't know about this event type.", eventType));
  109. }
  110. }
  111. private void OnListenerRemoved(string eventType)
  112. {
  113. if (eventTable[eventType] == null)
  114. {
  115. eventTable.Remove(eventType);
  116. }
  117. }
  118. private void OnBroadcasting(string eventType)
  119. {
  120. #if REQUIRE_LISTENER
  121. if (!eventTable.ContainsKey(eventType))
  122. {
  123. throw new BroadcastException(string.Format("Broadcasting message \"{0}\" but no listener found. Try marking the message with Messenger.MarkAsPermanent.", eventType));
  124. }
  125. #endif
  126. }
  127. private BroadcastException CreateBroadcastSignatureException(string eventType)
  128. {
  129. return new BroadcastException(string.Format("Broadcasting message \"{0}\" but listeners have a different signature than the broadcaster.", eventType));
  130. }
  131. public class BroadcastException : Exception
  132. {
  133. public BroadcastException(string msg): base(msg)
  134. {
  135. }
  136. }
  137. public class ListenerException : Exception
  138. {
  139. public ListenerException(string msg): base(msg)
  140. {
  141. }
  142. }
  143. // -- 2. 添加事件
  144. //No parameters
  145. public void AddListener(string eventType, Callback handler)
  146. {
  147. OnListenerAdding(eventType, handler);
  148. eventTable[eventType] = (Callback)eventTable[eventType] + handler;
  149. }
  150. //Single parameter
  151. public void AddListener<T>(string eventType, Callback<T> handler) {
  152. if (handler == null ){
  153. return;
  154. }
  155. OnListenerAdding(eventType, handler);
  156. eventTable[eventType] = (Callback<T>)eventTable[eventType] + handler;
  157. }
  158. //Two parameters
  159. public void AddListener<T, U>(string eventType, Callback<T, U> handler)
  160. {
  161. if (handler == null ){
  162. return;
  163. }
  164. OnListenerAdding(eventType, handler);
  165. eventTable[eventType] = (Callback<T, U>)eventTable[eventType] + handler;
  166. }
  167. //Three parameters
  168. public void AddListener<T, U, V>(string eventType, Callback<T, U, V> handler)
  169. {
  170. if (handler == null ){
  171. return;
  172. }
  173. OnListenerAdding(eventType, handler);
  174. eventTable[eventType] = (Callback<T, U, V>)eventTable[eventType] + handler;
  175. }
  176. // -- 3. 删除事件
  177. //No parameters
  178. public void RemoveListener(string eventType, Callback handler)
  179. {
  180. if (handler == null){
  181. return;
  182. }
  183. OnListenerRemoving(eventType, handler);
  184. if (eventTable.ContainsKey(eventType))
  185. {
  186. eventTable[eventType] = (Callback)eventTable[eventType] - handler;
  187. OnListenerRemoved(eventType);
  188. }
  189. }
  190. //Single parameter
  191. public void RemoveListener<T>(string eventType, Callback<T> handler)
  192. {
  193. if (handler == null){
  194. return;
  195. }
  196. OnListenerRemoving(eventType, handler);
  197. if (eventTable.ContainsKey(eventType))
  198. {
  199. eventTable[eventType] = (Callback<T>)eventTable[eventType] - handler;
  200. OnListenerRemoved(eventType);
  201. }
  202. }
  203. //Two parameters
  204. public void RemoveListener<T, U>(string eventType, Callback<T, U> handler)
  205. {
  206. if (handler == null){
  207. return;
  208. }
  209. OnListenerRemoving(eventType, handler);
  210. if (eventTable.ContainsKey(eventType))
  211. {
  212. eventTable[eventType] = (Callback<T, U>)eventTable[eventType] - handler;
  213. OnListenerRemoved(eventType);
  214. }
  215. }
  216. //Three parameters
  217. public void RemoveListener<T, U, V>(string eventType, Callback<T, U, V> handler)
  218. {
  219. if (handler == null){
  220. return;
  221. }
  222. OnListenerRemoving(eventType, handler);
  223. if (eventTable.ContainsKey(eventType))
  224. {
  225. eventTable[eventType] = (Callback<T, U, V>)eventTable[eventType] - handler;
  226. OnListenerRemoved(eventType);
  227. }
  228. }
  229. // -- 4. 广播事件
  230. //No parameters
  231. public void Broadcast(string eventType)
  232. {
  233. if (eventType == null ){
  234. return;
  235. }
  236. #if LOG_ALL_MESSAGES || LOG_BROADCAST_MESSAGE
  237. Debug.Log("MESSENGER\t" + System.DateTime.Now.ToString("hh:mm:ss.fff") + "\t\t\tInvoking \t\"" + eventType + "\"");
  238. #endif
  239. OnBroadcasting(eventType);
  240. Delegate d;
  241. if (eventTable.TryGetValue(eventType, out d))
  242. {
  243. Callback callback = d as Callback;
  244. if (callback != null)
  245. {
  246. List<Callback> removedDel = new List<Callback>();
  247. foreach(Delegate del in callback.GetInvocationList() ){
  248. //Debug.Log(" del is " + del.Target.GetType().ToString() );
  249. bool isCalled = false;
  250. if (del.Target is MonoBehaviour){
  251. MonoBehaviour mono = (MonoBehaviour)del.Target;
  252. if (mono != null){
  253. Callback cb = (Callback)del;
  254. isCalled = true;
  255. cb();
  256. }
  257. }else if (del.Target!=null){
  258. Callback cb = (Callback)del;
  259. isCalled = true;
  260. cb();
  261. }
  262. if (!isCalled){
  263. YmDebug.Log("the object represent is null " + eventType );
  264. removedDel.Add((Callback)del);
  265. }
  266. }
  267. if (eventTable.ContainsKey(eventType)){
  268. foreach (Callback rDel in removedDel)
  269. {
  270. callback = callback - rDel;
  271. }
  272. eventTable[eventType] = callback;
  273. }
  274. }
  275. else
  276. {
  277. YmDebug.LogCR("callback is destroyed ");
  278. // throw CreateBroadcastSignatureException(eventType);
  279. }
  280. }
  281. }
  282. //Single parameter
  283. public void Broadcast<T>(string eventType, T arg1)
  284. {
  285. if (eventType == null ){
  286. return;
  287. }
  288. #if LOG_ALL_MESSAGES || LOG_BROADCAST_MESSAGE
  289. Debug.Log("MESSENGER\t" + System.DateTime.Now.ToString("hh:mm:ss.fff") + "\t\t\tInvoking \t\"" + eventType + "\"");
  290. #endif
  291. OnBroadcasting(eventType);
  292. Delegate d;
  293. if (eventTable.TryGetValue(eventType, out d)) {
  294. Callback<T> callback = d as Callback<T>;
  295. if (callback != null)
  296. {
  297. List<Callback<T>> removedDel = new List<Callback<T>>();
  298. foreach(Delegate del in callback.GetInvocationList() ){
  299. //Debug.Log(i + " del is " + del.Target.GetType().ToString() );
  300. bool isCalled = false;
  301. if (del.Target is MonoBehaviour){
  302. MonoBehaviour mono = (MonoBehaviour)del.Target;
  303. if (mono != null){
  304. Callback<T> cb = (Callback<T>)del;
  305. cb(arg1);
  306. isCalled = true;
  307. }
  308. }else if (del.Target!=null){
  309. Callback<T> cb = (Callback<T>)del;
  310. cb(arg1);
  311. isCalled = true;
  312. }
  313. if (!isCalled){
  314. removedDel.Add((Callback<T>)del);
  315. }
  316. }
  317. if (eventTable.ContainsKey(eventType)){
  318. foreach (Callback<T> rDel in removedDel)
  319. {
  320. callback = callback - rDel;
  321. }
  322. eventTable[eventType] = callback;
  323. }
  324. }
  325. else
  326. {
  327. YmDebug.LogCR("callback is destroyed ");
  328. // throw CreateBroadcastSignatureException(eventType);
  329. }
  330. }
  331. }
  332. //Two parameters
  333. public void Broadcast<T, U>(string eventType, T arg1, U arg2)
  334. {
  335. if (eventType == null ){
  336. return;
  337. }
  338. #if LOG_ALL_MESSAGES || LOG_BROADCAST_MESSAGE
  339. Debug.Log("MESSENGER\t" + System.DateTime.Now.ToString("hh:mm:ss.fff") + "\t\t\tInvoking \t\"" + eventType + "\"");
  340. #endif
  341. OnBroadcasting(eventType);
  342. Delegate d;
  343. if (eventTable.TryGetValue(eventType, out d))
  344. {
  345. Callback<T, U> callback = d as Callback<T, U>;
  346. if (callback != null)
  347. {
  348. List<Callback<T, U>> removedDel = new List<Callback<T, U>>();
  349. foreach(Delegate del in callback.GetInvocationList() ){
  350. //Debug.Log(i + " del is " + del.Target.GetType().ToString() );
  351. bool isCalled = false;
  352. if (del.Target is MonoBehaviour){
  353. MonoBehaviour mono = (MonoBehaviour)del.Target;
  354. if (mono != null){
  355. Callback<T, U> cb = (Callback<T, U>)del;
  356. cb(arg1, arg2);
  357. isCalled = true;
  358. }
  359. }else if (del.Target!=null){
  360. Callback<T, U> cb = (Callback<T, U>)del;
  361. cb(arg1, arg2);
  362. isCalled = true;
  363. }
  364. if (!isCalled){
  365. removedDel.Add((Callback<T, U>)del);
  366. }
  367. }
  368. if (eventTable.ContainsKey(eventType)){
  369. foreach (Callback<T, U> rDel in removedDel)
  370. {
  371. callback = callback - rDel;
  372. }
  373. eventTable[eventType] = callback;
  374. }
  375. }
  376. else
  377. {
  378. YmDebug.LogCR("callback is destroyed ");
  379. // throw CreateBroadcastSignatureException(eventType);
  380. }
  381. }
  382. }
  383. //Three parameters
  384. public void Broadcast<T, U, V>(string eventType, T arg1, U arg2, V arg3)
  385. {
  386. if (eventType == null ){
  387. return;
  388. }
  389. #if LOG_ALL_MESSAGES || LOG_BROADCAST_MESSAGE
  390. Debug.Log("MESSENGER\t" + System.DateTime.Now.ToString("hh:mm:ss.fff") + "\t\t\tInvoking \t\"" + eventType + "\"");
  391. #endif
  392. OnBroadcasting(eventType);
  393. Delegate d;
  394. if (eventTable.TryGetValue(eventType, out d))
  395. {
  396. Callback<T, U, V> callback = d as Callback<T, U, V>;
  397. if (callback != null)
  398. {
  399. List<Callback<T, U, V>> removedDel = new List<Callback<T, U, V>>();
  400. foreach(Delegate del in callback.GetInvocationList() ){
  401. //Debug.Log(i + " del is " + del.Target.GetType().ToString() );
  402. bool isCalled = false;
  403. if (del.Target is MonoBehaviour){
  404. MonoBehaviour mono = (MonoBehaviour)del.Target;
  405. if (mono != null){
  406. Callback<T, U, V> cb = (Callback<T, U, V>)del;
  407. cb(arg1, arg2, arg3);
  408. isCalled = true;
  409. }
  410. }else if (del.Target!=null){
  411. Callback<T, U, V> cb = (Callback<T, U, V>)del;
  412. cb(arg1, arg2, arg3);
  413. isCalled = true;
  414. }
  415. if (!isCalled){
  416. removedDel.Add((Callback<T, U, V>)del);
  417. }
  418. }
  419. if (eventTable.ContainsKey(eventType)){
  420. foreach (Callback<T, U, V> rDel in removedDel)
  421. {
  422. callback = callback - rDel;
  423. }
  424. eventTable[eventType] = callback;
  425. }
  426. }
  427. else
  428. {
  429. YmDebug.LogCR("callback is destroyed ");
  430. // throw CreateBroadcastSignatureException(eventType);
  431. }
  432. }
  433. }
  434. // todo:
  435. public void DelayBroadcast(float d)
  436. {
  437. }
  438. }