1. View保存对Mediator对象的引用 。由Mediator对象来操作具体的视图组件(View Component,例如Flex的DataGrid组件),包括:添加事件监听器 ,发送或接收Notification ,直接改变视图组件的状态。这样做实现了把视图和控制它的逻辑分离开来。
当用View注册Mediator时,Mediator的listNotifications方法会被调用,以数组形式返回该Mediator对象所关心的所有Notification。之后,当系统其它角色发出同名的Notification(通知)时,关心这个通知的Mediator都会调用handleNotification方法并将Notification以参数传递到方法。
public function registerMediator( mediator:IMediator ) : void
{
// do not allow re-registration (you must to removeMediator fist)
if ( mediatorMap[ mediator.getMediatorName() ] != null ) return;
// Register the Mediator for retrieval by name
mediatorMap[ mediator.getMediatorName() ] = mediator;
// Get Notification interests, if any.
var interests:Array = mediator.listNotificationInterests();
// Register Mediator as an observer for each of its notification interests
if ( interests.length > 0 )
{
// Create Observer referencing this mediator's handlNotification method
var observer:Observer = new Observer( mediator.handleNotification, mediator );
// Register Mediator as Observer for its list of Notification interests
for ( var i:Number=0; i<interests.length; i++ ) {
registerObserver( interests[i], observer );
}
}
// alert the mediator that it has been registered
mediator.onRegister();
}
2. Controller 保存所有Command 与 Notification 的映射。Command是无状态的,只在需要时被创建。
public function registerCommand( notificationName : String, commandClassRef : Class ) : void
{
if ( commandMap[ notificationName ] == null ) {
view.registerObserver( notificationName, new Observer( executeCommand, this ) );
}
commandMap[ notificationName ] = commandClassRef;
}
public function executeCommand( note : INotification ) : void
{
var commandClassRef : Class = commandMap[ note.getName() ];
if ( commandClassRef == null ) return;
var commandInstance : ICommand = new commandClassRef();
commandInstance.execute( note );
}