【问题标题】:Mediator as a Singleton调解员作为单身人士
【发布时间】:2013-04-25 15:54:04
【问题描述】:

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

每个同事(在这种情况下是每个项目和网格)都应该知道它的 Mediator 对象。 (Design Patterns, Gamma et al.) 正因为如此,我想知道让这个中介器成为单例是否会被认为是一个好的设计选择。中介者是完全无状态的,并且对于每个对象都是相同的,从而满足单例模式规定的适用性要求。

【问题讨论】:

  • 单例引入耦合,每个人都可以访问单例。这被认为是不好的。

标签: design-patterns singleton mediator


【解决方案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&lt;[enum], Action&lt;T&gt;&gt; 进行调解。这门课是我修改的,但最初取自here。它说的是 MVVM,但它没有理由不能在其他实现中工作。

这是一个单例中介,可以如链接文章中所示使用。

希望对您有所帮助,对于迟到的回复深表歉意。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多