Sunday, September 7, 2008

Observer Pattern

Observer Pattern: When objects have a one to many relationship, i.e. many objects need to be updated when one object changes, and the number of these objects is not known ahead of time, this pattern can be used to implement it.

We begin by implementing 2 interfaces:
  • IObservable: This is the object that gets observed - whose change would affect other objects
  • IObserver: This represents objects that are the observers
Here is a pseudo-code implementation of the interfaces:

Interface IObservable {
// The attachObserver function adds the passed object to an array
public function attachObserver(obj);
// The detachObserver function removes the passed object from the array
public function detachObserver(obj);
// Notify all the objects in the array - loop through the objects and call the update method
// Note: All the elements in the array implement the IObserver interface and hence
// support the "update" method
public function notify();
// Function would be called by the Observers to get state information about the object
public function getState();
}

Interface IObserver {
// The method that performs the action that needs to be done on change of the observable
public function update();
}

The actual observer and observable classes would implement these interfaces.

Two examples of where you might be using this:
  • In a web application, you may register screens with your business model objects (representing underlying data) - hence when the model gets updated, the screens get updated automatically.
  • Another example may be, say you are making a game - and you when 1 object performs a task - such as a commander issuing a fire order, all units within the commanders range should fire (they would have registered with the commander object - and as they observed a change, they perform an action).
We have covered what the observer pattern is, how it is coded, and two examples of where it may be used. The answer for the why is the same as why use design patterns (see the post on Design Patterns in general). With that I will end this post. I hope someone, someday, somewhere (may be myself) will find this useful. :)

Labels:

1 Comments:

Post a Comment

<< Home