Created
November 14, 2014 13:16
-
-
Save Zeroto/8e5ac7945e93f4e50a3a to your computer and use it in GitHub Desktop.
EventManager
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
namespace Events | |
{ | |
class EventManager | |
{ | |
private static EventManager instance = null; | |
public static EventManager Instance | |
{ | |
get | |
{ | |
if (instance == null) | |
instance = new EventManager(); | |
return instance; | |
} | |
} | |
private EventManager() | |
{ | |
} | |
private Dictionary<Type, MulticastDelegate> listeners = new Dictionary<Type, MulticastDelegate>(); | |
public void SendEvent<T>(T eventData) | |
{ | |
MulticastDelegate d; | |
if (listeners.TryGetValue(typeof(T), out d)) | |
{ | |
System.Action<T> e = (System.Action<T>)d; | |
e(eventData); | |
} | |
} | |
public void RegisterListener<T>(System.Action<T> listener) | |
{ | |
MulticastDelegate d; | |
if (listeners.TryGetValue(typeof(T), out d)) | |
{ | |
var e = (System.Action<T>)d; | |
e += listener; | |
listeners[typeof(T)] = e; | |
} | |
else | |
{ | |
listeners[typeof(T)] = listener; | |
} | |
} | |
public void RemoveListener<T>(System.Action<T> listener) | |
{ | |
MulticastDelegate d; | |
if (listeners.TryGetValue(typeof(T), out d)) | |
{ | |
var e = (System.Action<T>)d; | |
e -= listener; | |
listeners[typeof(T)] = e; | |
} | |
} | |
public void Clear() | |
{ | |
listeners.Clear(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment