Part 2 of 6 · 2 min read
The idea
One-to-many, loosely coupled.
Think of a newspaper subscription. The newspaper does not know its readers by name or by habit. It keeps a list of subscribers and delivers each issue to all of them. A reader can join or cancel at any time, and the newspaper does not change.
GoF's intent for Observer is a link from one object to many others: whenever the one changes, each of the others is told and refreshes itself without being asked. The object that changes is the subject. The ones that follow it are observers.
Take a meeting room board. When a room becomes busy or free, a wall screen must refresh, a mail service may send a message, and a report may log the change. If the board called each of these directly, it would depend on every one of them, and adding a fourth would mean editing the board. With Observer, the board knows only a small interface and a list of things that implement it.
GoF points out what this buys. Each side can change on its own. A subject can be reused without its observers and the reverse, and a new observer needs no edit to the subject or to the other observers. The subject only knows that it holds objects with one simple interface, so the tie between them is small and abstract. An observer can even sit in a different layer of the system from the subject, so the layering stays clean.
Observer pattern
The Observer pattern lets an object, the subject, keep a list of other objects, the observers, and notify them all when it changes, without knowing what they are.
Example: a RoomBoard that tells a screen and a mail service when room A1 becomes busy.
Check yourself: 1. What does the subject know about its observers? 2. Why can an observer live in a different layer? 3. What happens to the board if a fourth observer is added?