Question

I'm working on a school project about GRAPS and Design Patterns. It's basically a game with a grid on which objects as well as players can move. I was thinking about using a mediator to determine the exact location on which an object should land.

Each colleague (in this case each item and the grid) should be aware of it's Mediator object. (Design Patterns, Gamma et al.) Because of this, I was wondering whether making this mediator a singleton would be considered a good design choice. The mediator is completely stateless and is identical for each object, thereby meeting the applicability requirements stated by the Singleton pattern.

Was it helpful?

Solution

I know it is late but please check the following Mediator implementation...

public sealed class Mediator
{
    private static Mediator instance = null;
    private volatile object locker = new object();
    private MultiDictionary<ViewModelMessages, Action<Object>> internalList =
        new MultiDictionary<ViewModelMessages, Action<object>>();

    #region Constructors.
    /// <summary>
    /// Internal constructor.
    /// </summary>
    private Mediator() { }

    /// <summary>
    /// Static constructor.
    /// </summary>
    static Mediator() { }
    #endregion

    #region Properties.
    /// <summary>
    /// Instantiate the singleton.
    /// </summary>
    public static Mediator Instance
    {
        get
        {
            if (instance == null)
                instance = new Mediator();
            return instance;
        }
    }
    #endregion

    #region Public Methods.
    /// <summary>
    /// Registers a Colleague to a specific message.
    /// </summary>
    /// <param name="callback">The callback to use 
    /// when the message it seen.</param>
    /// <param name="message">The message to 
    /// register to.</param>
    public void Register(Action<Object> callback, ViewModelMessages message)
    {
        internalList.AddValue(message, callback);
    }

    /// <summary>
    /// Notify all colleagues that are registed to the 
    /// specific message.
    /// </summary>
    /// <param name="message">The message for the notify by.</param>
    /// <param name="args">The arguments for the message.</param>
    public void NotifyColleagues(ViewModelMessages message, object args)
    {
        if (internalList.ContainsKey(message))
        {
            // forward the message to all listeners.
            foreach (Action<object> callback in internalList[message])
                callback(args);
        }
    }
    #endregion
}

This class uses a Dictionary<[enum], Action<T>> to mediate. This class was ammended by me, but was origonally taken from here. It says MVVM, but there is no reason why it cannot work in other implementations.

This is a singleton mediator and can be used as shown in the linked article.

I hope this helps and sorry for the late reply.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top