Saturday, 28 May 2011

The Observer Pattern

Having written two blogs that mentioned the Observer pattern, I thought that I’d talk about it more formally, mainly because the Wikipedia entry for this pattern is a bit rubbish: the Java example given doesn’t implement the class diagram shown and uses the flawed Observer, Observable classes instead. Looking back at my GOF Design Patterns book, the actual pattern should be something like this:

This is just my UML interpretation: the GOF used Rumbaugh's OMT notation in their work. If you need a good pattern book, seek out Head First Design Patterns.

The Observer pattern defines a one-to-many dependency between objects so that when the observed subject changes, all its dependencies are notified and updated. This is sometimes known as publish and subscribe.

This pattern is usually used when a change in one object (the subject) requires changing one or more others, and it's not known in advance which objects need to change and the objects are not directly coupled other than by this pattern.

The Java JDK pattern uses the UML model below and has the benefit in that it does a lot of the work for you, in terms of controlling the Observers, but has the drawback of using inheritance over aggregation

As Joshua Bloch states in Item 16 of Effective Java you should “favor composition over inheritance”.

So, more on how to implement the Observer pattern using the aggregation later.

No comments: