What is the Observer pattern?
Why Interviewers Ask This
Candidates at the intermediate level are expected to not only know this concept but explain the trade-offs involved. Interviewers use this question to see if you can reason about design decisions, not just recall facts.
Answer
The Observer pattern defines a one-to-many dependency — when one object (Subject/Publisher) changes state, all dependent objects (Observers/Subscribers) are automatically notified. Interfaces: interface Observer { void update(Event event); } interface Subject { void addObserver(Observer observer); void removeObserver(Observer observer); void notifyObservers(Event event); }. Implementation: class StockMarket implements Subject { private List<Observer> observers = new ArrayList<>(); private Map<String, Double> prices = new HashMap<>(); @Override public void addObserver(Observer o) { observers.add(o); } @Override public void removeObserver(Observer o) { observers.remove(o); } @Override public void notifyObservers(Event event) { for (Observer o : observers) { o.update(event); } } public void updatePrice(String symbol, double newPrice) { prices.put(symbol, newPrice); notifyObservers(new PriceChangeEvent(symbol, newPrice)); } } class StockAlertBot implements Observer { private String targetSymbol; private double alertPrice; public StockAlertBot(String symbol, double alertPrice) { this.targetSymbol = symbol; this.alertPrice = alertPrice; } @Override public void update(Event event) { if (event instanceof PriceChangeEvent pce) { if (pce.symbol().equals(targetSymbol) && pce.price() >= alertPrice) { System.out.println("ALERT: " + targetSymbol + " hit $" + pce.price()); } } } } StockMarket market = new StockMarket(); market.addObserver(new StockAlertBot("AAPL", 200.0)); market.addObserver(new StockAlertBot("TSLA", 300.0)); market.updatePrice("AAPL", 205.0); // Triggers AAPL alert. Real-world uses: event systems (JavaScript addEventListener), MVC (Model notifies Views), reactive streams, GUI frameworks, publish-subscribe systems (Kafka, RabbitMQ conceptually).
Pro Tip
Before answering, structure your response: one-line definition → real-world analogy → concrete example from a project. This makes even complex OOP Concepts answers easy to follow.