Home > Assignments > Recipe for Success: Implementing the Observer Pattern

Recipe for Success: Implementing the Observer Pattern

Probably the most difficult thing when implementing the Observer Pattern is realizing where you actually need to use it. In some cases it may be very obvious, but in other cases you might have a minor, unnoticed relationship that would greatly benefit from the Observer Pattern. I imagine that sometimes it might be easier to realize the necessity for the pattern when you’re actually doing the nitty-gritty coding.

Here are the steps:

  1. Realize what relationships within your program would benefit from the Observer Pattern. These relationship may be one-to-one or one-to-many.
  2. Figure out which objects within your relationship will be the Observers and which will be the Subject (Observable). This step actually proves to be quite troublesome as you might feel that the Observer Pattern is backwards when you begin to implement the code. The solution to this problem is to take a step back and look at all your objects within your relationship. Now, realize which objects change. The objects that change will be the Subject (Observable). The goal is that when your Subject changes, all the Observers will get new information.
  3. Now that you’ve figured which objects will be the Subject (Observable) and which will be the Observers, you need to extend and implement the Observable class and the Observer interface. Here lies one of the patterns major downfalls: you must extend. Since Java does not allow multiple inheritance, if you’ve already created a class hierarchy and you’re attempting to implement the pattern, you can’t. You simply cannot. You must redefine your hierarchy, or move the extension to the super class. If you’re using the prebuilt Java Observable class and Observer interface, you don’t have to do much. All you need to do is define the update() method within your Observer class, and define when your Subject (Observable) will call notifyObservers().
  4. Your Observers will receive an Object that is the Subject through the update() method. You must then decide what your Observers want to do with the Subject they’re observing. You can either have the Observers pull the information they want from their Subject, or you may have the Subject send out all its information that changes to all its Observers.
Advertisements
Categories: Assignments Tags: ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: