View RSS Feed

My Java Tips

The Observer Design Pattern

Rate this Entry
by , 11-20-2011 at 06:00 PM (1840 Views)
The Observer design pattern is a Behavioral design pattern. It is used to observe the state of an object in the program. In Observer pattern object(s) are registered to observe an event that may be raised by the observed object. Simply put the Observer pattern allows one object called the observer to watch another object called the subject.


The observer pattern can listen to an external event, for example a user action. The observer pattern is also used to create a loose coupling between the model and the view in the Model View Controller design pattern. The observer pattern is used in almost all GUI toolkits. Within Java itself there are a many examples of the Observer pattern: the Java AWT or Swing event model, as well as the java.util.Observer and java.util.Observable interfaces to name a few.



The participant classes in the Observer pattern are:

Subject

It is a abstract class which provides an interface for attaching and detaching observers, as well as it holds a private list of observers. It contain functions attach(), detach() and notify().

ConcreteSubject

It sends notification to all its observers. It has function getState().

Observer

It consists noify() method and this class is used as an abstract class.

ConcreteObserver

It maintains relation with class ConcreteSubject. It has notify() function.

The example below uses the Observer design pattern. It takes input from keyboard and treats each input line as an event. When a string is sent from keyboard, the method notifyObservers is invoked to in order to inform all observers of the event.

Java Code:
import java.util.Observable;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class EventGenerator extends Observable implements Runnable
{
    public void run()
    {
        try
        {
            final InputStreamReader isr = new InputStreamReader( System.in );
            final BufferedReader br = new BufferedReader( isr );
            while( true )
            {
                final String response = br.readLine();
                setChanged();
                notifyObservers( response );
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}

import java.util.Observable;
import java.util.Observer;  

public class Responder implements Observer
{
    private String resp;
    public void update (Observable obj, Object arg)
    {
        if (arg instanceof String)
        {
            resp = (String) arg;
            System.out.println("nReceived Response: "+ resp );
        }
    }
}

public class ObserverDemo
{
    public static void main(String args[])
    {
        System.out.println("Enter Text: ");
        final EventGenerator evSrc = new EventGenerator();
       final Responder respHandler = new Responder();
        evSrc.addObserver( respHandler );
       Thread thread = new Thread(evSrc);
        thread.start();
    }
}

Submit "The Observer Design Pattern" to Facebook Submit "The Observer Design Pattern" to Digg Submit "The Observer Design Pattern" to del.icio.us Submit "The Observer Design Pattern" to StumbleUpon Submit "The Observer Design Pattern" to Google

Comments