Observer Pattern in Java

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

I’m Iman

Mein Name ist Iman Dabbaghi. Ich arbeite als Senior Software Engineer in der Schweiz. Außerdem interessiere ich mich sehr für gewaltfreie Kommunikation, Bachata-Tanz und Musik sowie fürs die Persönlichkeitsentwicklung.

Ich habe einen Masterabschluss in Informatik von der Universität Freiburg in Deutschland, bin Spring/Java Certified Professional (OCP), Certified Professional for Software Architecture (CPSA-F) und ein lebenslanger Lernender 🎓.

EN:

My name is Iman Dabbaghi. I work as a Senior Software Engineer in Switzerland. I am also very interessted in nonviolent communication, Bachata dance and music and also for personal development.

I hold a masters degree in computer science from the university of Freiburg in Germany, am a Spring / Java Certified Professional (OCP), Certified Software Architecture (CPSA-F) and Life Long Learner🎓

Let’s connect