调解员作为单身人士

时间:2013-04-25 15:54:04

标签: design-patterns singleton mediator

我正在开展一个关于GRAPS和设计模式的学校项目。它基本上是一个带有网格的游戏,对象和玩家都可以在这个网格上移动。我正在考虑使用中介来确定物体应落在的确切位置。

每个同事(在这种情况下,每个项目和网格)都应该知道它的Mediator对象。 (设计模式,Gamma等人)因此,我想知道将这个调解员变成单身是否会被认为是一个很好的设计选择。介体完全是无状态的,并且对于每个对象是相同的,从而满足Singleton模式所述的适用性要求。

1 个答案:

答案 0 :(得分:1)

我知道现在已经晚了但请检查以下Mediator实施......

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
}

此课程使用Dictionary<[enum], Action<T>>进行调解。这堂课由我推荐,但最初取自here。它说MVVM,但没有理由不能在其他实现中工作。

这是一个单独的调解员,可以按照链接文章中的说明使用。

我希望这对迟到的回复有所帮助和抱歉。