2013-04-25 47 views
2

我正在研究关于GRAPS和设计模式的学校项目。它基本上是一个有对象和球员可以移动的网格的游戏。我正在考虑使用中介来确定物体应该着陆的确切位置。作为Singleton的调解员

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

+0

Singleton引入耦合,每个人都可以访问单例。这被认为是不好的。 – 2013-05-10 12:23:14

回答

1

我知道已经晚了,但请检查下面的调解员执行...

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,但没有理由不能在其他实现中工作。

这是一个单身介体,可以按照链接文章中所示使用。

我希望这有助于和迟到的答复抱歉。