Monday, May 19, 2014

Mediator Pattern/Class

 This is my Mediator class.  Right now I'm using it like a singleton but it can be changed back to a normal class easily.  The template "T" allows you to use whatever kind of key you like.  You can use any number of keys and have any number of Actions (functions/methods) registered under them.  Using the Call method allows you to execute all functions/methods under the given Key and pass to them (the functions/methods) any object you desire.

public class Mediator<T>
 {
     private static Mediator<T> _Instance = new Mediator<T>();
 
     private Dictionary<T, List<Action<object>>> 
         _Callbacks = new Dictionary<T, List<Action<object>>>();
 
     private Mediator() { }
 
     public static Mediator<T> Instance
     {
         get
         {
             return _Instance;
         }
     }
 
     public static void Register(T Key, Action<object> Action)
     {
         if (!Instance._Callbacks.ContainsKey(Key))
         {
             Instance._Callbacks[Key] = new List<Action<object>>();
         }
 
         Instance._Callbacks[Key].Add(Action);
     }
 
     public static void Unregister(T Key, Action<object> Action)
     {
         Instance._Callbacks[Key].Remove(Action);
 
         if (Instance._Callbacks[Key].Count == 0)
         {
             Instance._Callbacks.Remove(Key);
         }
     }
 
     public static void Call(T Key, object Message = null)
     {
         if (Instance._Callbacks.ContainsKey(Key))
         {
             Instance._Callbacks[Key].ForEach(Action => Action(Message));
         }
     }
 }


A couple side notes:

First, not having code specific formatting is making my ass twitch.  I need to find a way to remedy that to make the code easier to read.  At least it's keeping the tabbing, right?

Second, since this is my first code post I would like to make it clear that I am open to any and all suggestions in regards to improving my code.  Constructive criticism, while sometimes hard to swallow, is almost always welcome.

[Edit]

So the solutions to the code specific formatting appears to be installing Productivity Power Tools for MSVS 20## (whatever version you're using.)  This is done and now you can see my code in all its colorful glory!

No comments:

Post a Comment