Observer Pattern: Event-Driven Logic

How does Flipkart notify 5 different services when you place an order? Master the Observer pattern to build decoupled, reactive systems that scale.

April 22, 20242 min read2 / 2

The Observer Design Pattern solves the problem of one class needing to notify many other classes when a specific event occurs--without those classes knowing about each other.

The Problem: The Dependency Explosion

Imagine an OrderService. When an Order is Placed, it needs to:

  1. Update Inventory.
  2. Generate Invoice.
  3. Send Email.
  4. Send SMS.

If you hardcode these calls in OrderService, your class becomes too rigid. If you want to add a "Push Notification" service later, you have to modify the OrderService.

The Solution: The "Notice Board"

Think of a teacher putting exam results on a Notice Board. The teacher doesn't call every student individually. The students (the observers) watch the board and act on their own.

Java Implementation

Java
public interface OrderObserver { void update(Order order); } public class OrderService { private List<OrderObserver> observers = new ArrayList<>(); public void addObserver(OrderObserver o) { observers.add(o); } public void placeOrder(Order order) { // ... business logic ... for (OrderObserver o : observers) { o.update(order); } } }

Java vs. JavaScript Perspective

1. In Java (Synchronous & Typed)

In standard Java, observers are usually notified synchronously. However, in enterprise systems like Spring, we use @EventListener to handle these events, often asynchronously to avoid blocking the main thread.

2. In JavaScript / TypeScript (The "Pub/Sub" King)

The Observer pattern is the heart of the web!

  • DOM Events: button.addEventListener('click', ...) is exactly the Observer pattern.
  • State Management: In Redux or Vue, components are "Observers" that watch the global state and re-render when it changes.
  • Node.js: The EventEmitter class is the built-in way to handle this pattern at scale.

Observer vs. Pub/Sub

While similar, there is a key difference:

  • Observer: The Subject directly calls the Observers (it knows who they are).
  • Pub/Sub: There is a "Broker" (like Kafka or a Message Bus) between them. The Subject just sends a message to the broker and doesn't care who receives it.

Great job! You've successfully navigated the core of the Behavioral Patterns. You're now ready to build systems that are truly responsive and decoupled!