Skip to the guide

Observer

BeginnerPattern7 pages

Observer lets one object tell many others that something changed, without knowing who they are or what they do about it. The 1994 book Design Patterns gives its intent as "define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically." Interviewers listen for what happens when a listener misbehaves, and for when a plain call is the better design.

A school's call list on a stormy morning

Think of a school on a stormy morning. The head decides to close, and the secretary works down a list of parents' phone numbers, saying the same sentence to each: "School is closed today." She doesn't know what each family does next. One phones a grandmother, and another stays home. Parents join by signing the list at the office, and they leave by crossing out their name.

Three things can go wrong on her round. A phone may be busy, so she notes it and carries on. A parent may cross out a name while she is calling, so she works from a copy printed before she starts. And a family who moved away and never crossed out their name still gets a call on every stormy morning.

In code, the school is this page's Auction, and the list is its listeners field. Signing and crossing out are subscribe and unsubscribe. Her one sentence is the one method every listener answers, bidPlaced(bid), written in the BidListener interface. The families are the listener classes, such as BidScreen and OutbidNotices, and each does its own thing with the news.