Design Patterns

Observer Pattern

The Observer pattern explained: a subject keeps a list of observers and notifies them all when its state changes. Code, common uses, pitfalls and pub/sub.

  • 6 min read
  • 5 questions
  • +35 XP
Transcript

Observer pattern explained by cats. Kitty love routines. It's tuna time. Mama Kitty wants to call all little kitties. Mama do not want to go to each one. Mama Kitty rings a bell. All the other kitties are subscribed. They instantly get the message and run to the food bowl.

This is the observer pattern. One subject, many observers. The subject just triggers an event. It doesn't need to know who's listening. Add a new little kitty. It subscribes to the bell. Remove a little kitty. It unsubscribes. No change to the bell.

Just who listen. In code, the bell is your subject. Each little kitty is an observer. Observers register to get updates. When the subject changes state, it notifies all observers. Observer pattern decouples the broadcaster from the listeners. Perfect for events, UI updates, notifications, and reactive systems. That's the observer pattern.