Observer Pattern

Observer Pattern

The observer 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. Observer is also a key part in the familiar MVC architectural pattern.

Related patterns: Publish–subscribe pattern, mediator, singleton.

Structure:

Observer Pattern

Definition
The essence of the Observer Pattern is to “Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically. “.

Below Example
Below is an example that takes keyboard input and treats each input line as an event. The example is built upon the library classes java.util.Observer [2] and java.util.Observable [3]. When a string is supplied from System.in, the method notifyObservers is then called, in order to notify all observers of the event’s occurrence, in the form of an invocation of their ‘update’ methods – in our example,ResponseHandler.update(…).

The file MyApp.java contains a main() method that might be used in order to run the code.

EventSource class:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Observable;

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

ResponseHandler Class:

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

public class ResponseHandler 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);
		}
	}

}

Main test program :

public class MyApp {
	public static void main(String[] args) {
		System.out.println("Enter Text >");
		// create an event source - reads from stdin
		final EventSource eventSource = new EventSource();
		// create an observer
		final ResponseHandler responseHandler = new ResponseHandler();
		// subscribe the observer to the event source
		eventSource.addObserver(responseHandler);
		// starts the event thread
		Thread thread = new Thread(eventSource);
		thread.start();
	}
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *