Event Broker: 通过发布事件源和订阅事件源来完成对象之间的协作
在实际应用中,我们可以使用EventBroker来进行发布和订阅事件通知以实现对象间的通信。通常做法都会把EventBroker实现为单例模式,我们在项目里是通过MEF的使用实现了EventBroker的单例模式:
public class EventSubscriptionToken { private EventSubscriptionToken(){} public static EventSubscriptionToken GetNewToken() { var guid = Guid.NewGuid().ToString(); var token = new EventSubscriptionToken {Value = guid}; return token; } public string Value { get; private set; } } public interface IEventBroker { void Publish<T>(T eventArgs); EventSubscriptionToken Subscribe<T>(Action<T> callback); bool Unsubscribe(EventSubscriptionToken subscriptionToken); } [Export(typeof(IEventBroker))] public class EventBroker : IEventBroker { private readonly IDictionary<string, object> _callbacksDictionary; [ImportingConstructor] public EventBroker() { _callbacksDictionary = new Dictionary<string, object>(); } public void Publish<T>(T eventArgs) { var callbacksToBeInvoked = _callbacksDictionary.Where(x => x.Value is Action<T>); foreach (var callback in callbacksToBeInvoked) { var actionCallback = (Action<T>)callback.Value; try { actionCallback(eventArgs); } catch (Exception) { } } } public EventSubscriptionToken Subscribe<T>(Action<T> callback) { var token = EventSubscriptionToken.GetNewToken(); _callbacksDictionary.Add(token.Value, callback); return token; } public bool Unsubscribe(EventSubscriptionToken subscriptionToken) { return _callbacksDictionary.Remove(subscriptionToken.Value); } }
事件的订阅实例:
_eventBroker.Subscribe<ModelNameChangedEvent>(EntityChangedEventHandler); private void EntityChangedEventHandler(ModelNameChangedEvent obj) { ... }
事件的订阅者不需要知道事件是由哪个对象发布的,双方是通过参数进行交互,订阅者根据传入的参数对象进行相应的操作以完成对象间的协作。
事件的发布实例:
_eventBroker.Publish(new ModelNameChangedEvent(entity.ID, entity.SpaceType, entity.Name));
在需要交互时通过参数对象发布出事件。