Observer Pattern: Event Notification
Implement Observer to decouple event producers from consumers in a stock price system.
The Observer Intent
Observer (also called Publish-Subscribe) defines a one-to-many dependency: when the subject changes state, all registered observers are notified automatically.
Subject and Observer Interfaces
The subject tracks a list of observers and notifies them. Observers implement an update method to react to events.
public interface Observer {
void update(String event, Object data);
}
public interface Subject {
void addObserver(Observer o);
void removeObserver(Observer o);
void notifyObservers(String event, Object data);
}All lessons in this course
- Observer Pattern: Event Notification
- Strategy Pattern: Interchangeable Algorithms
- Command Pattern: Encapsulating Actions
- Template Method: Defining Algorithm Skeletons