Sep 082011
 

You may hear of “Observer” or “Listener” somewhere especially when working with Swing or AWT. Do they have a difference? Some guys may even confuse between Observer and Listener, while actually they are the same concept in Java.

What is Observer Pattern?

Observer is a Behavior Design Pattern defined by GoF and the definition is maybe like this: “The observer pattern (a subset of the publish/subscribe pattern) is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods. It is mainly used to implement distributed event handling systems.” – from wiki.

Now let me take you to a closer look by observing an example:

observer pattern example thumb Observer Pattern Java Example

As you can read from the diagram, I will use a cellphone (BlackBerry in this case) to demonstrate this pattern. Each time there’s a call or an sms coming, a BlackBerry can notify you by multiple ways: via the ringtone, via a LED indicator or or via the Vibration…I treat these devices as the Observer object which will subscribe the SMSReceiver all the time for new SMS. If new SMS comes, these devices will be notified by the SMSReceiver to work accordingly.

Observer Pattern Example in Java

Now let’s see how we will explain the above example again in Java language.

blackberry sms receiver thumb Observer Pattern Java Example

First I will define the BBObserver object that can make BlackBerry device do something when some event happens.

package net.searchdaily.java.design.pattern.observer;

/**
 * Observer pattern example by searchdaily.net
 * 
 * @author namnvhue
 * 
 */
public interface BBObserver {
	public void handleEvent();
}

Next is for the BBObservable object that can contain a list of subscriber object, and when some other objects tell it, it will notify all other subscribers about the event.

Continue reading »