There are two places where you could use delegates in the Observer pattern. Since I'm not sure which one you are referring to, I will try to answer both.
First, the use of delegates in the subject instead of the IObservers list. This approach seems a lot cleaner when handling multicast, since you basically have
private delegate void UpdateHandler(string message); private UpdateHandler Update; public void Register(IObserver observer) { Update+=observer.Update; } public void Unregister(IObserver observer) { Update-=observer.Update; } public void Notify(string message) { Update(message); }
instead
public Subject() { observers = new List<IObserver>(); } public void Register(IObserver observer) { observers.Add(observer); } public void Unregister(IObserver observer) { observers.Remove(observer); } public void Notify(string message) {
If you don’t need to do anything special and require a reference to the entire IObserver object, I would think that delegates would be cleaner.
The second case is using pass delegates instead of IObervers, for example
public delegate void UpdateHandler(string message); private UpdateHandler Update; public void Register(UpdateHandler observerRoutine) { Update+=observerRoutine; } public void Unregister(UpdateHandler observerRoutine) { Update-=observerRoutine; } public void Notify(string message) { Update(message); }
However, observers do not need to implement an interface. You could even convey a lambda expression. This change in level of control is largely a difference. Whether it is good or bad is up to you.
Jacob Adams Nov 19 '08 at 18:47 2008-11-19 18:47
source share