The Observer Pattern defines a one-to-many dependency between objects. When one object (the Subject) changes state, all its dependents (the Observers) are notified and updated automatically. This is the heart of every modern UI framework and event-driven system.
In C#, we don't usually build Observe() and Notify() methods from scratch. We use the event keyword. This is the Observer pattern baked into the language.
public class StockTicker
{
// The SUBJECT
public event Action<decimal> OnPriceChanged;
public void UpdatePrice(decimal p) => OnPriceChanged?.Invoke(p);
}
// THE OBSERVERS
ticker.OnPriceChanged += (p) => Console.WriteLine($"UI updated: {p}");
ticker.OnPriceChanged += (p) => Logger.Log(p);
The StockTicker has NO IDEA which classes are listening to it. You can add 50 new listeners (mobile app, email service, audit log) without changing a single line of logic in the ticker. This is the ultimate tool for handling "Secondary Effects."
Q: "What is the danger of the Observer pattern in C# if you forget to 'Unsubscribe'?"
Architect Answer: "Memory Leaks. When you write `ticker.OnPriceChanged += ObserverMethod;`, the Subject (ticker) now holds a strong reference to your observer class in its internal delegate list. As long as the ticker is alive, the Garbage Collector refuses to delete your observer, even if you are 'done' with it. This is a very common leak in WPF and long-running services. You MUST always use `-=` or implement `IDisposable` to clean up your subscriptions."