In order to implement the Observer pattern in C#, one of the ways to go (at least, the one I chose) is to make classes that implement the IObservable<T>
for the observable objects and the IObserver<T>
for the observers.
In a project of mine I created a base class from which every observable inherits:
public class Observable<T> : IObservable<T>
{
private SubscriptionManager<T> _subscriptionManager;
public Observable()
{
_subscriptionManager = new SubscriptionManager<T>(
new List<IObserver<T>>());
}
public IDisposable Subscribe(IObserver<T> observer)
{
_subscriptionManager.Subscribe(observer);
return _subscriptionManager;
}
public void Notify(T obj)
{
_subscriptionManager.Notify(obj);
}
}
and an IDisposable
class that manages the subscriptions to the observable object:
public class SubscriptionManager<T> : IDisposable
{
private ICollection<IObserver<T>> _observers;
private IObserver<T> _observer;
public SubscriptionManager(ICollection<IObserver<T>> observers)
{
if (observers == null)
{
throw new ArgumentNullException("observers");
}
_observers = observers;
}
public void Subscribe(IObserver<T> observer)
{
_observers.Add(observer);
_observer = observer;
}
public void Notify(T obj)
{
foreach (var observer in _observers)
{
observer.OnNext(obj);
}
}
public void Dispose()
{
_observers.Remove(_observer);
}
}
Do you see anything that can be done more efficiently, or in a better way? Do you see anything else that may be wrong?