Observer

Defines a one-to-many dependency so that multiple objects are notified when one changes.

Context

When a product's price changes, several components must react (cache, view, alerts, metrics).

Problem
  • Calling everyone from the producer couples it to each consumer.
  • Every new consumer forces a change to the producer.
Solution

The subject maintains a list of observers and notifies them; each observer implements a common interface.

#Example in C# — event

public class PriceFeed
{
    public event EventHandler<decimal>? PriceChanged;
    public void Update(decimal p) => PriceChanged?.Invoke(this, p);
}

public class Logger
{
    public Logger(PriceFeed feed) => feed.PriceChanged += (_, p) => Console.WriteLine(
quot;Precio: {p}"); }

In C#, event + EventHandler or IObservable<T> already implement Observer.

When NOT to use it
  • When there is a single observer: a direct call is clearer.
  • When the order of notification matters: it becomes unpredictable.
Tradeoffs
Pro Con
Decouples producer and consumer Hard to follow flow in debugger
Allows adding consumers without touching producer Risk of memory leaks due to unremoved handlers

#Variants

  • Push (sends data to observer) vs Pull (notifies and observer queries).
  • IObservable<T> / Rx (reactive streams).

#behavioral #gof #events