A continuation in my self-assigned crash course in design patterns, I’ve been learning more about the observer pattern recently. It’s a cool pattern, and I’m hoping I can convince some of you that it’s worth learning more about. I only have time for a quick post, and hopefully I can get in the major points – but I WILL follow up on this with some example implementations.
High Level Overview
The observer pattern does exactly what it sounds like it should do – it allows one class to observe the changes made in another. Essentially, you have a class or set of classes (the subject), that inherit an abstract interface which will dictate the methods that they must implement in order to provide updates to their observer(s). The subjects don’t actually do the talking to their observers directly; there is always a layer of abstraction to ensure the subjects and observers are decoupled.
Coming from a web programming background, it may not be immediately apparent why the observer pattern is especially useful. This is because (in my opinion) web programs (with some exceptions) tend to have a very short runtime (meaning their execution starts when you load a page and concludes when the page finishes loading). So, even though we use the observer pattern in web programming (MVC springs to mind), I don’t think it’s usefulness and role are as readily apparent as in other contexts. In programs which are “on” until they are intentionally shut down (ie programs that run on an event loop, main loop, etc.), the importance of this pattern is much more obvious.
Here are some real world examples:
- The observer pattern forms the basis for how many GUI frameworks operate. It was first introduced in the SmallTalk language, which had an extremely strong influence on Apple and the evolution of their Objective C language. Many of the programs you use every day implement the observer pattern. Qt framework (c++), a GUI framework developed by Nokia, implements the observer pattern for Signal and Slot events – ie so your program knows when a button is pushed and can hook that update to the appropriate class / method. Java likewise implements a very similar signals / slots mechanism.
- Your web browser implements the observer pattern. You know that thing the DOM? Event listeners? onSomething(doThis)? Yea.
- Your cell phone implements the observer pattern. Your phone is always sitting there…waiting…just waiting for the network to tell it there is an inbound call.
…There are tons of other real world examples. At it’s core, the observer pattern is just a standardized way of separating cause and effect to reduce dependencies within a system. I hope this has been a decent beginner’s introduction!
Resources (best I’ve found)
Source Making: http://sourcemaking.com/design_patterns/observer
IBM Research: http://www.research.ibm.com/designpatterns/example.htm