Professional Documents
Culture Documents
The Observer Pattern is a behavioral design pattern that defines a one-to-many relationship
between objects so that when one object (the "subject" or "observable") changes state, all its
dependents (the "observers") are notified and updated automatically. This pattern is used to
establish a loose coupling between objects, allowing them to interact without being strongly
dependent on each other.
Key Participants
o Subject (Observable): This is the object that is being observed. It maintains a list of
observers and provides methods to register, remove, and notify observers when its state
changes.
o Observer: These are the objects that are interested in the state changes of the subject. They
implement an interface or abstract class that defines an update method. When the subject's
state changes, the update method of each observer is called.
Example: Weather Station
Suppose you are building a weather monitoring application. The weather station is the subject,
and various devices (e.g., displays, mobile apps, or notification systems) want to be updated
whenever the weather conditions change.
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
// Subject (Observable)
@Component
public class WeatherStation {
private List<WeatherObserver> observers = new ArrayList<>();
private double temperature;
private double humidity;
private double pressure;
// Observer
@Component
public class WeatherDisplay implements WeatherObserver {
@Override
public void update(double temperature, double humidity, double pressure) {
System.out.println("Weather Display: Temperature = " + temperature +
"°C, Humidity = " + humidity + "%, Pressure = " + pressure + " hPa");
}
}
// Observer
@Component
public class MobileApp implements WeatherObserver {
@Override
public void update(double temperature, double humidity, double pressure) {
System.out.println("Mobile App: Weather updated - " + temperature +
"°C, " + humidity + "%, " + pressure + " hPa");
}
}
// Observer interface
public interface WeatherObserver {
void update(double temperature, double humidity, double pressure);
}
In this Spring Boot example, we use the @Component annotation to define the WeatherStation,
WeatherDisplay, and MobileApp as Spring-managed beans. The WeatherStation serves as the
subject (observable), while WeatherDisplay and MobileApp are observers. The WeatherObserver
interface defines the update method that each observer implements.
Now, we can create a Spring Boot application class and use these components to demonstrate the
Observer Pattern's functionality.
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
@SpringBootApplication
public class WeatherApp {
weatherStation.addObserver(display);
weatherStation.addObserver(mobileApp);