Author: Wang Xuan Yi, source: http://www.cnblogs.com/neverdie/Reprinted, Please keep this statement. If you like this article, click [recommendation ]. Thank you!
Using UnityEngine; using System. collections; using System. collections. generic; // extended category of icationicationcenter. Here, we create multiple classes of inoicationicationcenter, and // process different message forwarding, so that the message group can be public class NotificationCenter: INotificationCenter {private static INotificationCenter singleton; private event EventHandler GameOver; private event EventHandler ScoreAdd; private icationicationcenter (): base () {// Add various messages to be distributed ev EntTable ["GameOver"] = GameOver; eventTable ["ScoreAdd"] = ScoreAdd;} public static INotificationCenter GetInstance () {if (singleton = null) singleton = new icationicationcenter (); return singleton; }}// the abstract base class public abstract class inotificationicationcenter {protected Dictionary <string, EventHandler> eventTable; protected INotificationCenter Center () {eventTable = new Dictionary <string, Event Handler> () ;}// PostNotification -- send the message with the name, sender, and parameter e to the 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) ;}// added or removed a callback function. Public void AddEventHandler (string name, EventHandler handler) {eventTable [name] + = handler;} public void RemoveEventHandler (string name, EventHandler handler) {eventTable [name]-= handler ;}}Abstract The Observer -- Introduce Observer
After joining icationcenter center, the next problem we need to face is that each of our observers needs to add a callback function in their own Start method and cancel the callback function in the OnDestroy method, we can abstract this part of code into an Observer component, use another dictionary to record all the callback functions registered with this GameObject, and cancel the subscription in the OnDestroy method of the Observer. The Code is as follows:
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); }}