top of page
stallonemacwan

Observer Pattern

An Observer Pattern says that "just define a one-to-one dependency so that when one object changes state, all its dependents are notified and updated automatically".

The observer pattern is also known as Dependents or Publish-Subscribe.


Benefits:

  • It describes the coupling between the objects and the observer.

  • It provides the support for broadcast-type communication.

Usage:

  • When the change of a state in one object must be reflected in another object without keeping the objects tight coupled.

  • When the framework we writes and needs to be enhanced in future with new observers with minimal chamges.

UML for Observer Pattern:



Implementation of Observer Pattern

Step 1:

Create a ResponseHandler1 class the will implement the java.util.Observer interface.

  1. import java.util.Observable;

  2. import java.util.Observer;

  3. public class ResponseHandler1 implements Observer {

  4. private String resp;

  5. public void update(Observable obj, Object arg) {

  6. if (arg instanceof String) {

  7. resp = (String) arg;

  8. System.out.println("\nReceived Response: " + resp );

  9. }

  10. }

  11. }


Step 2:

Create a ResponseHandler2 class the will implement the java.util.Observer interface.


  1. import java.util.Observable;

  2. import java.util.Observer;

  3. public class ResponseHandler2 implements Observer {

  4. private String resp;

  5. public void update(Observable obj, Object arg) {

  6. if (arg instanceof String) {

  7. resp = (String) arg;

  8. System.out.println("\nReceived Response: " + resp );

  9. }

  10. }

  11. }


Step 3:

Create an EventSource class that will extend the java.util.Observable class .


  1. import java.io.BufferedReader;

  2. import java.io.IOException;

  3. import java.io.InputStreamReader;

  4. import java.util.Observable;

  5. public class EventSource extends Observable implements Runnable {

  6. @Override

  7. public void run() {

  8. try {

  9. final InputStreamReader isr = new InputStreamReader(System.in);

  10. final BufferedReader br = new BufferedReader(isr);

  11. while (true) {

  12. String response = br.readLine();

  13. setChanged();

  14. notifyObservers(response);

  15. }

  16. }

  17. catch (IOException e) {

  18. e.printStackTrace();

  19. }

  20. }

  21. }


12 views0 comments

Recent Posts

See All

Comments


bottom of page