Skip to content

Instantly share code, notes, and snippets.

@Zeroto
Created November 14, 2014 13:16
Show Gist options
  • Save Zeroto/8e5ac7945e93f4e50a3a to your computer and use it in GitHub Desktop.
Save Zeroto/8e5ac7945e93f4e50a3a to your computer and use it in GitHub Desktop.
EventManager
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