The Observer pattern is a behavioral design pattern that defines a one-to-many dependency between objects. In this pattern, when the state of one object changes, all its dependents are notified and updated automatically. This helps in achieving loose coupling between objects and promotes reusability and maintainability of code.
In Java, the Observer pattern is implemented using the following interfaces and classes:
Observable: This is a class that represents the observable object or the subject. It maintains a list of its observers and provides methods to add or remove observers, as well as to notify them when its state changes.
Observer: This is an interface that represents the observer objects. It provides a single method called update() that is called by the observable object when its state changes.
Here’s an example implementation of the Observer pattern in Java:
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
public class Subject extends Observable {
private int state;
public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
setChanged();
notifyObservers();
}
}
public class ObserverA implements Observer {
@Override
public void update(Observable o, Object arg) {
System.out.println("ObserverA notified with state: " + ((Subject) o).getState());
}
}
public class ObserverB implements Observer {
@Override
public void update(Observable o, Object arg) {
System.out.println("ObserverB notified with state: " + ((Subject) o).getState());
}
}
public class Main {
public static void main(String[] args) {
Subject subject = new Subject();
ObserverA observerA = new ObserverA();
ObserverB observerB = new ObserverB();
subject.addObserver(observerA);
subject.addObserver(observerB);
subject.setState(1);
subject.setState(2);
}
}
In this example, the Subject class extends the Observable class and maintains its state as an integer value. It provides methods to get and set the state, and when the state is changed using the setState() method, it calls the setChanged() method to mark itself as changed, and then calls the notifyObservers() method to notify all its observers.
The ObserverA and ObserverB classes implement the Observer interface and define the update() method, which is called by the observable object when its state changes. These classes simply print the state value to the console.
In the Main class, we create an instance of the Subject class and two instances of the observer classes, ObserverA and ObserverB. We then add these observers to the subject using the addObserver() method. Finally, we change the state of the subject twice using the setState() method, and the observers are notified automatically with the new state values. The output of the program will be:
ObserverA notified with state: 1
ObserverB notified with state: 1
ObserverA notified with state: 2
ObserverB notified with state: 2