Intro to Java Observer Pattern

We are well into this whole patterns thing now, picking up lots of new lingo, and becoming better at communicating with other developers. Next on the list: the observer pattern. This is an important pattern to use to help prevent tight coupling and keep code separated into discrete objects. This pattern allows communication between two objects at particular times without each object needing to be too tightly coupled to the other.

The Observer in the Physical World

The idea behind the observer is like a subscription. Do you have a newspaper or magazine subscription? Have you signed up for cell phone texts from your favorite band when they have new tour dates? The act of you signing up with the newspaper, the magazine, or the band, is you saying you want a subscription, or that you want to become an observer. When the subject (newspaper, magazine, band) has something new to share (on a schedule or not) they run down their subscriber list, and notify the observers by mail, or text.

The Observer in the Software World

On the software side, the idea is the same. Your subject needs to provide a way to take subscriptions, hold a list of observers, and when a particular state changes, notify them. There is usually a couple of methods on the subject that takes in an interface that is used for getting on or off the subscription list. On this interface is also the “call back” method. This is the method that the subject will execute when it wants to inform the observers of state changes.
Continue reading