vexe

Delegate-based C# Event manager

Jan 2nd, 2014
182
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.89 KB | None | 0 0
  1. public static class EventManager
  2. {
  3.     public static void Subscribe<T>(Action<T> handler) where T : GameEvent
  4.     {
  5.         EventManagerInternal<T>.Subscribe(handler);
  6.     }
  7.     public static void Unsubscribe<T>(Action<T> handler) where T : GameEvent
  8.     {
  9.         EventManagerInternal<T>.Unsubscribe(handler);
  10.     }
  11.     public static void Raise<T>(T e) where T : GameEvent
  12.     {
  13.         EventManagerInternal<T>.Raise(e);
  14.     }
  15.     private static class EventManagerInternal<T> where T : GameEvent
  16.     {
  17.         private static Dictionary<Type, Action<T>> dic = new Dictionary<Type, Action<T>>();
  18.         public static void Subscribe(Action<T> handler)
  19.         {
  20.             Type type = typeof(T);
  21.             if (!dic.ContainsKey(type)) {
  22.                 dic[type] = handler;
  23.                 Console.WriteLine("Registered new type: " + type);
  24.             }
  25.             else {
  26.                 // make sure the handler doesn't exist first
  27.                 bool hasHandlerSubscribed = dic[type].GetInvocationList().Any(h => h.Equal(shandler));
  28.                 if (hasHandlerSubscribed) {
  29.                     Console.WriteLine(handler.Method.Name + " has already subbed to an event of type " + type);
  30.                     return;
  31.                 }
  32.                 dic[type] += handler;
  33.             }
  34.             Console.WriteLine("Method " + handler.Method.Name + " has subbed to receive notifications from " + type);
  35.         }
  36.         public static void Unsubscribe(Action<T> handler)
  37.         {
  38.             Type type = typeof(T);
  39.  
  40.             // make sure the type exists
  41.             if (!dic.ContainsKey(type)) {
  42.                 Console.WriteLine("Type " + type + " hasn't registered at all, it doesn't have any subscribers... at least not in my book...");
  43.                 return;
  44.             }
  45.  
  46.             // remove the handler from the chain
  47.             dic[type] -= handler;
  48.  
  49.             // if there's no more subscribers to the "type" entry, remove it
  50.             if (dic[type] == null) {
  51.                 dic.Remove(type);
  52.                 Console.WriteLine("No more subscribers to " + type);
  53.             }
  54.         }
  55.         public static void Raise(T e)
  56.         {
  57.             Action<T> handler;
  58.             if (dic.TryGetValue(e.GetType(), out handler)) {
  59.                 handler.Invoke(e);
  60.             }
  61.         }
  62.     }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment