Previous | Home | Next |
The Observer pattern is used in GUI Application. in this if any object change the state of itself then the other dependents object automatically update itself according to the object.
- The dependent object can change the state automatically.
- The One object change affects on one or many objects.
- It is maintain consistent between objects.
- It is Need broadcast communication.
Example
As we know that Observer pattern is even used in GUI application. For example, We can define an one-to-many relational dependency between objects by this when an object changes our state, then all dependent object are automatically update. The Java API is provide a built-in interface Observer and class Observable for dependency between the objects.
package r4r; import java.util.Observable; //Observable class is here import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class obj2 extends Observable implements Runnable { public void run() { try { final InputStreamReader ISR = new InputStreamReader( System.in ); final BufferedReader bu = new BufferedReader( ISR ); while( true ) { String response = bu.readLine(); setChanged(); notifyObservers( response ); } } catch (IOException e) { e.printStackTrace(); } } } package r4r; import java.util.Observable; import java.util.Observer; // this is Event Handler class public class obj1 implements Observer { private String res; public void update (Observable obj, Object arg) { if (arg instanceof String) { res = (String) arg; System.out.println("\nReceiving the Response: "+ res ); } } } //Create the Main class package r4r; import java.util.Observable; import java.util.*; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class observertest { public static void main(String args[]) { System.out.println("Enter The Text here>"); // create an event source - reads from stdin final obj1 ob1 = new obj1(); // create an observer final obj2 ob2 = new obj2(); // subscribe the observer to the event source ob1.addObserver(ob2); // starts the event thread Thread thread = new Thread(ob2); thread.start(); } }
Previous | Home | Next |