Architecture & Patterns110 min total · 26 parts
ACID, SOLID, and Design Patterns: A Complete Software Design Reference
Part 20 of 26 · ~1 min
Behavioral Patterns: Observer
Observer gives one object — call it the subject — a standing list of dependents to automatically notify the instant its state changes, with the subject never needing to know a single concrete thing about who's on that list.
public class ShiftRoster
{
// C# events are a built-in, language-level implementation of Observer.
public event Action<int, int>? SlotFilled; // (shiftId, remainingSlots)
private int _remainingSlots;
public int RemainingSlots
{
get => _remainingSlots;
set
{
_remainingSlots = value;
SlotFilled?.Invoke(ShiftId, _remainingSlots); // notify every subscriber, whatever it is
}
}
public int ShiftId { get; init; }
}
public class FrontDeskDashboard
{
public void OnSlotFilled(int shiftId, int remaining) => Console.WriteLine($"Shift {shiftId}: {remaining} left");
}
var roster = new ShiftRoster { ShiftId = 88 };
var dashboard = new FrontDeskDashboard();
roster.SlotFilled += dashboard.OnSlotFilled; // subscribe
roster.RemainingSlots = 2; // triggers OnSlotFilled automatically
This is a pattern you've already used even if you've never called it Observer by name — a browser's addEventListener, a message queue's pub/sub model, and a plain C# event are all this same idea wearing different clothes, and in every one of them the publisher genuinely has no way to know, at compile time, who's subscribed or how many listeners there are. The failure mode that only shows up once an application has been running a while is a subscription nobody ever tore down. A coordinator closes one site's dashboard and opens another; if the closed dashboard's handler was never unhooked from SlotFilled, it keeps sitting in the roster's invocation list, invisible, still firing on every slot change for a screen that no longer exists anywhere on anyone's machine. Nothing crashes. Nothing logs a warning. Memory just quietly holds on to more than it should, for longer than anyone intended.