Objects that subclass the Observable class maintain a list of observers. When an Observable object is updated it invokes the update() method of each of its observers to notify the observers that it has changed state. The Observer interface is implemented by objects that observe Observable objects.
In Java, the Observer
and Observable
classes were part of the java.util package to implement the Observer design pattern. However, as of Java 9, the Observable
class has been deprecated, and the preferred approach is to use the java.beans
package or other custom implementations for implementing the Observer pattern.
The Observer pattern is a behavioral design pattern where an object, known as the subject, maintains a list of its dependents, called observers, that are notified of any changes in the subject’s state. The Observer
interface declares the update
method, which is called by the subject to notify the observer of a state change.
Here’s a brief explanation of how the Observer pattern can be implemented in Java:
- Subject (Observable): The object being observed. It maintains a list of observers and provides methods to add, remove, and notify observers.
java
import java.util.Observable;
public class Subject extends Observable {
private int state;public int getState() {
return state;
}public void setState(int state) {
this.state = state;
setChanged(); // Marks the subject as changed
notifyObservers(state); // Notifies observers with the new state
}
} - Observer: The interface that observers implement.
java
import java.util.Observer;
public class ConcreteObserver implements Observer {
public void update(Observable o, Object arg) {
// This method is called by the subject when its state changes
int newState = (int) arg;
System.out.println(“Received update. New state: “ + newState);
}
} - Main Application:
java
// Adding observer to the subjectpublic class Main {
public static void main(String[] args) {
Subject subject = new Subject();
ConcreteObserver observer = new ConcreteObserver();
subject.addObserver(observer);
// Changing the state of the subject will notify the observer
subject.setState(42);
}
}
Remember that with the deprecation of Observable
, it’s often recommended to create custom implementations of the Observer pattern or use alternatives provided in other libraries or frameworks. The usage of the java.beans
package with PropertyChangeSupport
and PropertyChangeListener
is one such alternative in Java.