简介
事件总线是对发布-订阅模式的一种实现,是一种集中式事件处理机制,允许不同的组件之间进行彼此通信而又不需要相互依赖,达到一种解耦的目的。
实现事件总线
EventBus维护一个事件的字典,发布者、订阅者在事件总线中获取事件实例并执行发布、订阅操作,事件实例负责维护、执行事件处理程序。流程如下:
定义事件基类
事件实例需要在事件总线中注册,定义一个基类方便事件总线进行管理,代码如下:
/// <summary>
/// 事件基类
/// </summary>
public abstract class EventBase{ }
事件实例需要管理、执行已经注册的事件处理程序,为了适应不同的事件参数使用泛型参数,不允许此类实例化。代码如下:
/// <summary>
/// 泛型事件
/// </summary>
/// <typeparam name="T"></typeparam>
public abstract class PubSubEvent<T> : EventBase where T : EventArgs
{
protected static readonly object locker = new object();
protected readonly List<Action<object, T>> subscriptions = new List<Action<object, T>>();
public void Subscribe(Action<object, T> eventHandler)
{
lock (locker)
{
if (!subscriptions.Contains(eventHandler))
{
subscriptions.Add(eventHandler);
}
}
}
public void Unsubscribe(Action<object, T> eventHandler)
{
lock (locker)
{
if (subscriptions.Contains(eventHandler))
{
subscriptions.Remove(eventHandler);
}
}
}
public virtual void Publish(object sender, T eventArgs)
{
lock (locker)
{
for (int i = 0; i < subscriptions.Count; i++)
{
subscriptions[i](sender, eventArgs);
}
}
}
}
定义事件参数基类
事件参数基类继承EventArgs,使用泛型参数适应不同的参数类型,不允许此类实例化。代码如下:
/// <summary>
/// 泛型事件参数
/// </summary>
/// <typeparam name="T"></typeparam>
public abstract class PubSubEventArgs<T> : EventArgs
{
public T Value { get; set; }
}
定义EventBus
EventBus只提供事件实例的管理,具体事件处理程序的执行由事件实例自己负责。为了使用方便,构造函数有自动注册事件的功能,在有多个程序集时可能会有bug。代码如下:
/// <summary>
/// 事件总线
/// </summary>
class EventBus
{
private static EventBus _default;
private static readonly object locker = new object();
private Dictionary<Type, EventBase> eventDic = new Dictionary<Type, EventBase>();
/// <summary>
/// 默认事件总线实例,建议只使用此实例
/// </summary>
public static EventBus Default
{
get
{
if (_default == null)
{
lock (locker)
{
// 如果类的实例不存在则创建,否则直接返回
if (_default == null)
{
_default = new EventBus();
}
}
}
return _default;
}
}
/// <summary>
/// 构造函数,自动加载EventBase的派生类实现
/// </summary>
public EventBus()
{
Type type = typeof(EventBase);
Type typePubSub = typeof(PubSubEvent<>);
Assembly assembly = Assembly.GetAssembly(type);
List<Type> typeList = assembly.GetTypes()
.Where(t => t != type && t != typePubSub && type.IsAssignableFrom(t))
.ToList();
foreach (var item in typeList)
{
EventBase eventBase = (EventBase)assembly.CreateInstance(item.FullName);
eventDic.Add(item, eventBase);
}
}
/// <summary>
/// 获取事件实例
/// </summary>
/// <typeparam name="TEvent">事件类型</typeparam>
/// <returns></returns>
public TEvent GetEvent<TEvent>() where TEvent : EventBase
{
return (TEvent)eventDic[typeof(TEvent)];
}
/// <summary>
/// 添加事件类型
/// </summary>
/// <typeparam name="TEvent"></typeparam>
public void AddEvent<TEvent>() where TEvent : EventBase ,new()
{
lock (locker)
{
Type type = typeof(TEvent);
if (!eventDic.ContainsKey(type))
{
eventDic.Add(type, new TEvent());
}
}
}
/// <summary>
/// 移除事件类型
/// </summary>
/// <typeparam name="TEvent"></typeparam>
public void RemoveEvent<TEvent>() where TEvent : EventBase, new()
{
lock (locker)
{
Type type = typeof(TEvent);
if (eventDic.ContainsKey(type))
{
eventDic.Remove(type);
}
}
}
}
使用事件总线
事件及事件参数
使用事件总线前,需要定义好事件及事件参数。在使用时,发布者、订阅者也必须知道事件类型及事件参数类型。代码如下:
/// <summary>
/// 泛型事件实现-TestAEvent,重写事件的触发逻辑
/// </summary>
public class TestAEvent: PubSubEvent<TestAEventArgs>
{
public override void Publish(object sender, TestAEventArgs eventArgs)
{
lock (locker)
{
for (int i = 0; i < subscriptions.Count; i++)
{
var action= subscriptions[i];
Task.Run(() => action(sender, eventArgs));
}
}
}
}
/// <summary>
/// 泛型事件参数实现-TestAEventArgs
/// </summary>
public class TestAEventArgs : PubSubEventArgs<string> { }
/// <summary>
/// 泛型事件实现-TestBEvent
/// </summary>
public class TestBEvent : PubSubEvent<TestBEventArgs> { }
/// <summary>
/// 泛型事件参数实现-TestBEventArgs
/// </summary>
public class TestBEventArgs : PubSubEventArgs<int> { }
注:TestAEvent中重写了事件发布的逻辑,每个事件在任务中执行。
定义发布者
发布者通过事件总线获取事件实例,在实例上发布事件,代码如下:
class Publisher
{
public void PublishTeatAEvent(string value)
{
EventBus.Default.GetEvent<TestAEvent>().Publish(this, new TestAEventArgs() { Value=value});
}
public void PublishTeatBEvent(int value)
{
EventBus.Default.GetEvent<TestBEvent>().Publish(this, new TestBEventArgs() { Value = value });
}
}
定义订阅者
订阅者通过事件总线获取事件实例,在实例上订阅事件,代码如下:
class ScbscriberA
{
public string Name { get; set; }
public ScbscriberA(string name)
{
Name = name;
EventBus.Default.GetEvent<TestAEvent>().Subscribe(TeatAEventHandler);
}
public void TeatAEventHandler(object sender, TestAEventArgs e)
{
Console.WriteLine(Name+":"+e.Value);
}
}
class ScbscriberB
{
public string Name { get; set; }
public ScbscriberB(string name)
{
Name = name;
EventBus.Default.GetEvent<TestBEvent>().Subscribe(TeatBEventHandler);
}
public void Unsubscribe_TeatBEvent()
{
EventBus.Default.GetEvent<TestBEvent>().Unsubscribe(TeatBEventHandler);
}
public void TeatBEventHandler(object sender, TestBEventArgs e)
{
Console.WriteLine(Name + ":" + e.Value);
}
}
实际使用
代码如下:
class Program
{
static void Main(string[] args)
{
Publisher publisher = new Publisher();
ScbscriberA scbscriberA = new ScbscriberA("scbscriberA");
ScbscriberB scbscriberB1 = new ScbscriberB("scbscriberB1");
ScbscriberB scbscriberB2 = new ScbscriberB("scbscriberB2");
publisher.PublishTeatAEvent("test");
publisher.PublishTeatBEvent(123);
scbscriberB2.Unsubscribe_TeatBEvent();
publisher.PublishTeatBEvent(12345);
Console.ReadKey();
}
}
运行结果:
scbscriberB1:123
scbscriberB2:123
scbscriberA:test
scbscriberB1:12345
总结
这个事件总线只提供了基础功能,实现的发布者和订阅者的解耦,发布者、订阅者只依赖事件不互相依赖。
感觉我对事件总线的理解还有点不足,欢迎大家来一起讨论!
参考资料
c# – 使用反射来发现派生类型
Prism.Core/Events/EventBase.cs
C# 事件总线 EventBus