Notification貫穿MVC三層,由Name(通知名/收件人)**與Body(內容)**組成。一個Notification可被多個Observer接收(1:N)。
// View層觀察者映射
observerMap = new Dictionary>();
// Observer屬性
private string _notifyMethod; // 回調方法名
private object _notifyContext; // 方法所屬對象
// 通知觸發
public void NotifyObserver(INotification notification)
{
var type = _notifyContext.GetType();
var flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase;
var method = type.GetMethod(_notifyMethod, flags);
method.Invoke(_notifyContext, new object[] { notification });
}
使用反射調用回調,靈活但有性能開銷。
現狀**:IView接口定義RegisterObserver/RemoveObserver/NotifyObservers,導致:
應用AOP原則,將觀察者管理從MVC縱向分層中橫向抽離:
Notifier直接向ObserverHub發送通知。View/Controller/Model均通過ObserverHub註冊關注點。
event/Action基礎實現。