The Observer Pattern

Clean Code, Episode 31

By Robert C. Martin

65 minMar 2015

OK, get ready for some fun. In this episode we're going to dive deep into the Observer pattern.

The first thing we'll do is derive the pattern from first principles. We'll begin with a simple real-time clock application and, step by step, apply one design principle after another until the Observer pattern emerges.

Well, actually, what emerges is a structure that our current most popular languages can't implement, because it requires multiple inheritance. So we'll explore the workarounds to that, and then we'll rant about why Java and C# don't have this useful feature.

The Observer pattern comes in two forms. The "Push" model, and the "Pull" model. We'll describe them both and discuss when and where each is appropriate.

Then we'll turn to the larger pattern that the Observer fits into: Model View Controller. We'll look at the history of MVC, and the unfortunate corruption of the pattern by current web frameworks.

Finally, we'll invoke the Humble Object pattern for testing GUIs, and we'll derive the Model View Presenter pattern from MVC.