Observer
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.
Observer or Publish/Subscribe in Java recognizable by behavioral methods which invokes a method on an instance of another abstract/interface type, depending on own state
java.util.Observer/java.util.Observable
(rarely used in real world though)- All implementations of
java.util.EventListener
(practically all over Swing thus) javax.servlet.http.HttpSessionBindingListener
javax.servlet.http.HttpSessionAttributeListener
javax.faces.event.PhaseListener
import java.util.Observable;
import java.util.Scanner;
class EventSource extends Observable implements Runnable {
public void run() {
while (true) {
String response = new Scanner(System.in).next();
setChanged();
notifyObservers(response);
}
}
}
import java.util.Observable;
import java.util.Observer;
public class MyApp {
public static void main(String[] args) {
System.out.println("Enter Text: ");
EventSource eventSource = new EventSource();
eventSource.addObserver(new Observer() {
public void update(Observable obj, Object arg) {
System.out.println("Received response: " + arg);
}
});
new Thread(eventSource).start();
}
}
/*
interface Observer{
public void update(Observable obj, Object arg);
}
*/