The Observer Pattern in Java is a design pattern where an object, called the subject, maintains a list of dependent objects, called observers, that are notified automatically of any changes to the subject. When the subject’s state changes, it updates all its observers without them needing to constantly check for changes.
Example:
Imagine a weather station (subject) that broadcasts temperature updates. Different displays (observers) subscribe to the station. When the temperature changes, the station automatically notifies all displays to update their readings.
import java.util.ArrayList;
import java.util.List;
class WeatherStation {
private List<Observer> observers = new ArrayList<();
private int temperature;
public void addObserver(Observer observer) {
observers.add(observer);
}
public void setTemperature(int temperature) {
this.temperature = temperature;
notifyAllObservers();
}
private void notifyAllObservers() {
for (Observer observer : observers) {
observer.update(temperature);
}
}
}
interface Observer {
void update(int temperature);
}
class Display implements Observer {
private String name;
public Display(String name) {
this.name = name;
}
@Override
public void update(int temperature) {
System.out.println(name + " display updated: Temperature is " + temperature + "°C");
}
}
public class Main {
public static void main(String[] args) {
WeatherStation station = new WeatherStation();
Display phoneDisplay = new Display("Phone");
Display windowDisplay = new Display("Window");
station.addObserver(phoneDisplay);
station.addObserver(windowDisplay);
station.setTemperature(25);
}
}
In this example, when the WeatherStation updates its temperature, it automatically notifies both Phone and Window displays to show the new temperature.

Hinterlasse einen Kommentar