The Observer Design Pattern(II)
10 March 2008This post is in continuation of The Observer Design Pattern(I). Do read that before this one.
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.
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(); } }
Related Posts:
- The Observer Design Pattern(I)
- Design Patterns - Basics (I)
- Singleton - Creational Design Pattern (I)
- The Strategy Design Pattern in Java(I)
- The Facade Design Pattern (I)
- Adapter design pattern
- The Strategy Design Pattern in Java(II)
- Introduction to Model View Controller Architecture (II)
- Design Patterns - Basics (II)
- The Facade Design Pattern (II)
Top Of Page | Trackback
If you found this page useful, consider linking to it. Simply copy and paste the code below into your web site.
It will look like this: The Observer Design Pattern(II)