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.

Time —Space —Code C#
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

In the .NET library

public event Action<int>? Freed; Freed?.Invoke(spotId); is the idiomatic C# form of the same design.