技术开发 频道

MVC模式结合Mediator模式的运用

   Mediator类完成Controller对象之间的协调,其定义如下:

public class Mediator
{
    MultiDictionary
<string, IColleague> internalList
        
= new MultiDictionary<string, IColleague>();

    
public void Register(IColleague colleague, IEnumerable<string> messages)
    {
        foreach (
string message in messages)
            internalList.AddValue(message, colleague);
    }

    
public void NotifyColleagues(string message, object args)
    {
        
if (internalList.ContainsKey(message))
        {
            
//forward the message to all listeners
            foreach (IColleague colleague in internalList[message])
                colleague.MessageNotification(message, args);
        }
    }
}
 

   Register()方法会将消息与Controller对象的映射注册到内部字典internalList中。而 NotifyColleagues()方法则会遍历整个internalList,然后执行Controller对象(体现为IColleague类型) 的MessageNotification()方法。通过MessageNotification()方法,每个Controller对象根据传输的消息字符 串,做出相应的响应操作。例如在FileSelectorController类中,就是根据Message的值,执行装载文件的业务逻辑:

public override void MessageNotification(string message, object args)
{
    switch (message)
    {
        
case Messages.DirectorySelectedChanged:
            
//load all files for the directory specified
            LoadFiles((DirectoryDisplayItem)args);
            break;
    }
}

   如果没有引入Mediator模式,由于需要在点击目录时显示当前目录的文件,因此在DirectorySelectorController类的 ItemSelected事件中,必须调用FileSelectorController对象获取文件信息,然后通过对应视图显示这些文件信息。这就导致 了DirectorySelectorController和FileSelectorController之间的依赖。现在,在 DirectorySelectorController的ItemSelected事件中,就可以通过Mediator来实现文件信息的读取与显示:

//event handler for the selecting changed
void ItemSelected(
object sender, RoutedEventArgs e)
{
    TreeView treeView
= (TreeView)e.OriginalSource;
    
//Send a message that an item is selected and pass the object selected
    Mediator.NotifyColleagues(Messages.DirectorySelectedChanged, treeView.SelectedItem);
}
0
相关文章