Monday, February 4, 2008

Observer Recipe

First you need to figure out which object(s) needs to be the subject and which ones need to be observers.

Then you must decide on whether to use Java's built in observer implementation or if you'd rather create your own infterfaces for Subject and Observer.

If you create your own, you must have methods in the Subject interface for adding and removing observers and for notifying observers that the subject's data has changed. Then in the Observer interface you must have a method for updating the observers with data from the subject.

You now need to implement the Subject and Observer interfaces in the appropriate classes so that you'll have one subject and many observers. The constructor of each observer class should register it with the subject class by calling registerObserver(this).

Now, you can either push out data, sending out whatever the subject has and letting the observers use what they want, or pull specific pieces data into the observers from the subject directly. The pull method requires more getter methods in the class that implements Subject, but seems like the better option in terms of keeping the observers on a need-to-know basis.

In the Subject class, you must create an arraylist to store the observers in and implement the subject interface. If you're going to push data, then you should create a dataChanged() method that will call notifyObservers() whenever the data is changed. notifyObservers() will iterate through the arraylist, pushing each observer the updated data. If you're going to pull data from the subject, let notifyObservers() cause the observer to use the getter methods of the subject class to pull the updated data.

Now, to test your implementation of the Observer Pattern, you need to create an instance of the subject class and observer classes. When you create the observer classes, pass the reference of the subject class to their constructor so that they will be added to the observers arraylist by their constructors.

When you change the data in the subject class, the dataChanged() method will be called, which will in turn call notifyObservers(). From here the new information will either be pushed or pulled to the observers.

If you use Java's built in observer, you don't need to worry about creating the two interfaces. You will need to have the subject class import and extend observable and the observer classes import and implement observer. You'll then need to use setChanged() and notifyObservers() to update the observers. Register observers with addObserver().

No comments: