Java Notes
Complete guide to Observer pattern — publish-subscribe mechanism, event handling, loose coupling, Java implementation with real-world examples.
Intent
Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
UML Structure
| Subject | Observer | |
|---|---|---|
| (interface) | (interface) | |
| + attach(Observer) | ───────▶ | + update(event) |
When to Use
- When changes in one object require changing others, and you don't know how many
- When an object should notify other objects without knowing who they are
- Event handling systems (GUI, message queues)
- Real-time data feeds (stock prices, notifications)
- MVC architecture (Model notifies Views)
Type-Safe Observer with Generics
// Generic event system
interface Observer<T> {
void onEvent(T event);
}
class EventBus<T> {
private final List<Observer<T>> observers = new CopyOnWriteArrayList<>();
public void subscribe(Observer<T> observer) {
observers.add(observer);
}
public void unsubscribe(Observer<T> observer) {
observers.remove(observer);
}
public void publish(T event) {
observers.forEach(o -> o.onEvent(event));
}
}
// Typed events
record OrderCreatedEvent(long orderId, String customer, double total) {}
record OrderShippedEvent(long orderId, String trackingNumber) {}
// Usage
EventBus<OrderCreatedEvent> orderBus = new EventBus<>();
orderBus.subscribe(event ->
System.out.println("Sending confirmation to: " + event.customer()));
orderBus.subscribe(event ->
System.out.println("Updating inventory for order: " + event.orderId()));
orderBus.publish(new OrderCreatedEvent(1001, "Alice", 99.99));Real-World: Stock Market Observer
class StockMarket {
private Map<String, Double> prices = new HashMap<>();
private Map<String, List<StockObserver>> watchers = new HashMap<>();
public void addStock(String symbol, double price) {
prices.put(symbol, price);
watchers.putIfAbsent(symbol, new ArrayList<>());
}
public void watch(String symbol, StockObserver observer) {
watchers.computeIfAbsent(symbol, k -> new ArrayList<>()).add(observer);
}
public void updatePrice(String symbol, double newPrice) {
double oldPrice = prices.getOrDefault(symbol, 0.0);
prices.put(symbol, newPrice);
double changePercent = ((newPrice - oldPrice) / oldPrice) * 100;
StockUpdate update = new StockUpdate(symbol, oldPrice, newPrice, changePercent);
watchers.getOrDefault(symbol, List.of())
.forEach(w -> w.onPriceChange(update));
}
}
interface StockObserver {
void onPriceChange(StockUpdate update);
}
record StockUpdate(String symbol, double oldPrice, double newPrice, double changePercent) {}
class AlertObserver implements StockObserver {
private double threshold;
public AlertObserver(double thresholdPercent) {
this.threshold = thresholdPercent;
}
@Override
public void onPriceChange(StockUpdate update) {
if (Math.abs(update.changePercent()) > threshold) {
System.out.printf("⚠️ ALERT: %s moved %.2f%% ($%.2f → $%.2f)%n",
update.symbol(), update.changePercent(), update.oldPrice(), update.newPrice());
}
}
}Observer with Java Built-in Support
Thread-Safe Observer
class ThreadSafeEventManager<T> {
private final List<Observer<T>> observers = new CopyOnWriteArrayList<>();
private final ExecutorService executor = Executors.newFixedThreadPool(4);
public void subscribe(Observer<T> observer) {
observers.add(observer);
}
public void unsubscribe(Observer<T> observer) {
observers.remove(observer);
}
// Synchronous notification
public void notifySync(T event) {
for (Observer<T> observer : observers) {
try {
observer.onEvent(event);
} catch (Exception e) {
System.err.println("Observer error: " + e.getMessage());
}
}
}
// Asynchronous notification
public void notifyAsync(T event) {
for (Observer<T> observer : observers) {
executor.submit(() -> {
try {
observer.onEvent(event);
} catch (Exception e) {
System.err.println("Async observer error: " + e.getMessage());
}
});
}
}
public void shutdown() {
executor.shutdown();
}
}Interview Questions
Q1: What is the Observer pattern and where is it used?
Answer: Observer defines a one-to-many dependency where subject state changes automatically notify all observers. Used in: event systems, GUI frameworks, MVC (Model→View), reactive programming, message brokers, and real-time updates.
Q2: What is the difference between Observer and Pub/Sub?
Answer: In Observer, subject knows about observers directly (tight coupling to interface). In Pub/Sub, publishers and subscribers are completely decoupled via a message broker/event bus. Pub/Sub is more scalable for distributed systems.
Q3: How do you prevent memory leaks with Observer?
Answer: Use weak references for observers, provide explicit unsubscribe methods, use CopyOnWriteArrayList for thread-safe iteration, and ensure long-lived subjects don't hold references to short-lived observers (common in Android/GUI).
Q4: What is the difference between push and pull models?
Answer: Push: subject sends all data in the update notification (observers may get data they don't need). Pull: subject sends minimal notification, observers query the subject for specific data they need. Push is simpler; Pull is more flexible.
Q5: Where is Observer used in Java standard library?
Answer: java.beans.PropertyChangeListener, java.util.EventListener, Swing listeners (ActionListener, MouseListener), JavaFX observable properties, java.util.concurrent.Flow (reactive streams since Java 9).
Summary
In this chapter, we learned about Observer Design Pattern in detail. Here are the key points:
- Basic introduction to the concept and why it is needed
- Syntax and structure with complete examples
- Internal working and best practices
- Real-world applications and use cases
- Common mistakes and how to avoid them
- How this topic is asked in interviews
To practice these concepts, write and run the code in your IDE and verify the output. Modify each example and experiment so that you deeply understand the concept.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Observer Design Pattern.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Java Master Course topic.
Search Terms
java-master-course, java master course, java, master, course, design, patterns, observer
Related Java Master Course Topics