作者:王選易,出處:http://www.cnblogs.com/neverdie/ 歡迎轉載,也請保留這段聲明。如果你喜歡這篇文章,請點【推薦】。謝謝!
using UnityEngine; using System; using System.Collections; using System.Collections.Generic; // NotificationCenter的拓展類,在這裡弄出多個INotificationCenter的子類, // 分別處理不同的消息轉發,便於消息分組 public class NotificationCenter : INotificationCenter { private static INotificationCenter singleton; private event EventHandler GameOver; private event EventHandler ScoreAdd; private NotificationCenter() : base() { // 在這裡添加需要分發的各種消息 eventTable["GameOver"] = GameOver; eventTable["ScoreAdd"] = ScoreAdd; } public static INotificationCenter GetInstance() { if (singleton == null) singleton = new NotificationCenter(); return singleton; } } // NotificationCenter的抽象基類 public abstract class INotificationCenter { protected Dictionary<string, EventHandler> eventTable; protected INotificationCenter() { eventTable = new Dictionary<string, EventHandler>(); } // PostNotification -- 將名字為name,發送者為sender,參數為e的消息發送出去 public void PostNotification(string name) { this.PostNotification(name, null, EventArgs.Empty); } public void PostNotification(string name, object sender) { this.PostNotification(name, name, EventArgs.Empty); } public void PostNotification(string name, object sender, EventArgs e) { if (eventTable[name] != null) { eventTable[name](sender, e); } } // 添加或者移除了一個回調函數。 public void AddEventHandler(string name, EventHandler handler) { eventTable[name] += handler; } public void RemoveEventHandler(string name, EventHandler handler) { eventTable[name] -= handler; } }
在加入了NotificationCenter之後,我們要面對的下一個問題就是,我們的每一個觀察者都需要在自己的Start方法中添加回調函數,在OnDestroy方法中取消回調函數,那麼,我們可以把這部分的代碼抽象在一個Observer組件中,使用另一個字典記載下所有的該GameObject注冊的回調函數,在Observer的OnDestroy方法裡面一次全部取消訂閱。代碼如下:
using UnityEngine; using System.Collections; using System.Collections.Generic; using System; public class Observer : MonoBehaviour { private INotificationCenter center; private Dictionary<string, EventHandler> handlers; void Awake() { handlers = new Dictionary<string, EventHandler>(); center = NotificationCenter.GetInstance(); } void OnDestroy() { foreach (KeyValuePair<string, EventHandler> kvp in handlers) { center.RemoveEventHandler(kvp.Key, kvp.Value); } } public void AddEventHandler(string name, EventHandler handler) { center.AddEventHandler(name, handler); handlers.Add(name, handler); } }