# Purpose
Establishes a subscription relation where objects (observers) are automatically notified of any change in the state of another object (subject).
# Problem
-
Subject-Observer Coupling: Need to notify changes without the subject knowing the concrete receiving classes.
-
Dynamic Update: Objects that need to monitor states that change over time.
# Solution
-
Subscription: Observers voluntarily register or unregister.
-
Automatic Notification: The subject iterates over its subscribers and calls their update method after a change.
# Structure
# Participants
- Subject: Interface for registration and notification.
- ConcreteSubject: The object of interest with changing state.
- Observer: Interface with the update() method.
- ConcreteObserver: The subscriber that reacts to changes.
# When to Use It
When a change in one object requires changes in others that are unknown a priori, or when the list of interested parties is dynamic.
# Advantages
-
verified
Decoupling: Subjects and observers evolve separately.
-
verified
Broadcast: Simultaneous notification to multiple classes.
# Disadvantages
-
warning
Unnecessary Updates: Receiving irrelevant notifications.
-
warning
Memory Leak: If subscribers are not unregistered.
# Example: Weather Alert
Weather station (Subject) notifying mobile Apps and news services (Observers).
# Java Code
interface Subject {
void register(Observer o);
void notifyObservers();
}
class WeatherData implements Subject {
private List<Observer> obs = new ArrayList<>();
public void notifyObservers() {
for (Observer o : obs) o.update(temp, hum, press);
}
}
# Mapping Participants
- WeatherData: ConcreteSubject.
- MobileApp: ConcreteObserver.
- Service: Client.
# Conclusions
It is the foundation of reactive systems and allows a highly extensible architecture against new monitoring requirements.
# Related Patterns
Mediator
To coordinate communication between complex objects.
Singleton
To ensure a central observer or a single global subject.