Observer: one change, many listeners
When a parking spot frees up, the display board, the app and the audit log all need to know, without the spot tracker knowing about each of them.
Watch it animatedStep through it, with the running line highlighted. Free with an account.The idea
The subject keeps a list of observers behind an interface and calls each one when something happens. New listeners subscribe without the subject changing. In C#, events and delegates are Observer built into the language.
Code
public interface ISpotObserver { void OnFreed(int spotId); }
public class SpotTracker
{
readonly List<ISpotObserver> _observers = new();
public void Subscribe(ISpotObserver o) => _observers.Add(o);
public void Free(int spotId)
{
foreach (var o in _observers) o.OnFreed(spotId);
}
}
public class DisplayBoard : ISpotObserver { public void OnFreed(int id) { /* +1 free */ } }
public class AppNotifier : ISpotObserver { public void OnFreed(int id) { /* push */ } }Tips
- Remember to unsubscribe; a forgotten observer keeps objects alive and causes memory leaks.
- If listeners are slow or remote, publish to a queue instead of calling them in the same thread.
- Observer inside one process; a message broker is the same idea across services.
In the .NET library
public event Action<int>? Freed; Freed?.Invoke(spotId); is the idiomatic C# form of the same design.