EventBus实现原理
#region
{
EventBus eventBus
= EventBus
.Instance
;
TeacherEventListener teacherEventListener
= new TeacherEventListener();
eventBus
.AddListener(teacherEventListener
);
Teacher teacher
= new Teacher();
TeacherSendNoticEvent teacherSendNoticEvent
= new TeacherSendNoticEvent(teacher
);
eventBus
.PublishEvent(teacherSendNoticEvent
);
}
#endregion
相关类
class EventBus
{
private EventBus() { }
private static EventBus _eventBus
= null;
public static EventBus Instance
{
get
{
return _eventBus
?? (_eventBus
= new EventBus());
}
}
private static ISet
<IEventListener
> eventListeners
= new HashSet<IEventListener>();
public void AddListener(IEventListener eventListener
)
{
eventListeners
.Add(eventListener
);
}
public void RemoveListener(IEventListener eventListener
)
{
eventListeners
.Remove(eventListener
);
}
public void PublishEvent(Event evnt
)
{
if (evnt
== null)
throw new ArgumentNullException("evnt");
foreach (var listener
in eventListeners
)
{
listener
.OnEvent(evnt
);
}
}
}
abstract class Event
{
public object source
{ get; }
protected Event(object source
)
{
this.source
= source
;
}
}
interface IEventListener
{
void OnEvent(Event @
event);
}
class ConnectionCloseEvent : Event
{
public ConnectionCloseEvent(object source
) : base(source
)
{
}
}
class ConnectionListener : IEventListener
{
public void OnEvent(Event @
event)
{
Console
.WriteLine("事件被触发了");
}
}
class TeacherEventListener : IEventListener
{
public void OnEvent(Event @
event)
{
throw new NotImplementedException();
}
}
class TeacherSendNoticEvent : Event
{
public TeacherSendNoticEvent(object source
) : base(source
)
{
}
}
转载请注明原文地址: https://lol.8miu.com/read-20562.html