在C#中,實(shí)現(xiàn)事件驅(qū)動的松耦合設(shè)計需要遵循一些關(guān)鍵原則。以下是一些建議:
public interface IEventHandler
{
void OnEventOccurred(object sender, EventArgs e);
}
public class WeakEventHandler<TEventArgs> where TEventArgs : EventArgs
{
private readonly WeakReference _handlerReference;
public WeakEventHandler(Action<object, TEventArgs> handler)
{
_handlerReference = new WeakReference(handler);
}
public void OnEventOccurred(object sender, TEventArgs e)
{
var handler = (Action<object, TEventArgs>)_handlerReference.Target;
if (handler != null && handler.Method != null)
{
handler(sender, e);
}
}
}
public class EventPublisher
{
public event IEventHandler EventOccurred;
protected virtual void OnEventOccurred(object sender, EventArgs e)
{
EventOccurred?.Invoke(this, e);
}
}
public class EventSubscriber : IEventHandler
{
public void OnEventOccurred(object sender, EventArgs e)
{
// 處理事件
}
}
var publisher = new EventPublisher();
var subscriber = new EventSubscriber();
var weakEventHandler = new WeakEventHandler<EventArgs>(subscriber.OnEventOccurred);
publisher.EventOccurred += weakEventHandler.OnEventOccurred;
遵循這些建議,可以在C#中實(shí)現(xiàn)基于事件的松耦合設(shè)計。