Coursify

Mastering Low Level Design (LLD)

Behavioral Patterns (Observer & Strategy)

25 mins

Learn how to manage object responsibilities and communication effectively using the Observer and Strategy patterns.

Learning Goals

  • Design event-driven systems using the Observer pattern.
  • Implement interchangeable algorithms using the Strategy pattern.
  • Analyze when to use behavioral patterns to reduce coupling in complex logic.

Managing Object Communication

Behavioral design patterns are concerned with algorithms and the assignment of responsibilities between objects. They don't just describe patterns of objects or classes but also the patterns of communication between them.

1. The Observer Pattern

The Observer pattern defines a one-to-many dependency between objects so that when one object (the Subject) changes state, all its dependents (Observers) are notified and updated automatically.

Real-world analogy: A newspaper subscription. When the publisher releases a new issue, all subscribers receive a copy.

Why use it? When a change to one object requires changing others, and you don't know how many objects need to be changed or who they are.

Implementing an Event Bus (Observer)

  1. 1
    Step 1

    Create an IObserver interface with an update(message) method. Any class that wants to listen for events must implement this.

  2. 2
    Step 2

    The Subject class maintains a private list of observers. It provides methods like subscribe(observer) and unsubscribe(observer).

  3. 3
    Step 3

    Add a notifyObservers(message) method to the Subject. This method iterates through the list of observers and calls update() on each one.

  4. 4
    Step 4

    When a state change occurs in the Subject (e.g., a new order is placed), it calls notifyObservers(). All registered listeners—like EmailService, InventoryService, and SmsService—react independently.

2. The Strategy Pattern

The Strategy pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

Visualizing Strategy

Why use it? When you have many related classes that differ only in their behavior, or when you need different variants of an algorithm.

Knowledge Check

Question 1 of 3
Q1Single choice

Which behavioral pattern is best for implementing a 'Subscription' or 'Event Listener' model?

Behavioral Patterns (Observer & Strategy) | Mastering Low Level Design (LLD) | Coursify