The Observer Pattern Coding Kata

The second design pattern I will be looking at is the Observer pattern, which is useful for safely passing data between objects. The Observer pattern is defined as:

“a one-to-many relationship between objects so that when one object changes state all it dependants are notified and updated automatically”.

A good analogy for this pattern, described in the excellent Head First Design Patterns book is that of a magazine publisher and subscribers. Here the publisher is the one in the relationship and the subscribers are the many. Typically the publisher will notify each of the subscribers of a new magazine edition by sending them the magazine in the post or through their e-book subscription. Translated into the Observer pattern the Publisher is known as the Subject and the subscribers are the observers. The subject notifies the observers of changes in its state.

Some important features to note about this pattern are:

  • Observers can not change the state of the subject and vice versa (ie. they are Loosely Coupled)
  • The state information can be either pushed out to the observers by the subject or pulled from the subject by the observers
  • Observers can be added and removed at any time

The brief

This is our fictitious brief for a new system which needs to be designed. It is election time and the polls are coming in. A local TV station would like us to design a system which can keep track of the results as they arrive. There are several hundred constituencies (areas of the country) which may declare for the Blue, Red, Yellow or Green party. The TV station wants to present this data in a number of ways:

  • As a leader board, showing the tally for each party
  • As a map, with each region coloured to the winning party
  • As a Swingometer showing the proportional change and overall result

We don’t need to worry about the implementation details of these display methods, the algorithms will be provided by the TV station. Our main concern is how to design a system to pass the data between the election object and the display objects.

Designing the Solution

Here is the class diagram for our solution, if you would like to try implementing the solution yourself the starting point for the kata is tagged here: Observer Pattern Kata Start.

Observer pattern for election data

We have leveraged the Observer pattern in our solution. The Election object inherits from ISubject and each of the display methods inherit from IObserver. The Election object maintains a list of the observers, we can add or remove an observer to this list using the Register and Unregister methods. When the subjects Notify method is called it informs each of the observers that a change has occurred by calling their Update method. A completed implementation for the election scenario is tagged here: Observer Pattern Kata End.

Comments

Copyright © 2016 - Hook Technologies Ltd - Powered by Octopress