Design Patterns interview question · Most asked

Explain the Observer pattern and give examples from real frameworks.

Summary

Observer lets a subject notify any number of subscribers when something happens, without knowing what they do. Subscribers register and unregister at runtime. Examples: DOM addEventListener, Node.js EventEmitter, RxJS, Laravel events and model observers, Django signals, Spring application events.

Longer Answer

It decouples the source of an event from its reactions: order placement doesn't import email, analytics and inventory code; they subscribe. Decide how ordering and errors are handled (one failing observer shouldn't break the subject unless it must), and always unsubscribe to avoid memory leaks.

Across processes or services, use Pub/Sub with a broker instead of in-process observers.

Code Example

class Events:
    def __init__(self):
        self.subscribers = []

    def subscribe(self, fn):
        self.subscribers.append(fn)

    def publish(self, order_id):
        for fn in self.subscribers:
            fn(order_id)


events = Events()
events.subscribe(lambda oid: print(f"email: receipt for {oid}"))
events.subscribe(lambda oid: print(f"stock: reserve for {oid}"))
events.publish(42)

Key Points

  • Subject notifies subscribers it doesn't know.
  • Subscribe/unsubscribe at runtime.
  • Handle observer errors and ordering deliberately.
  • Unsubscribe to avoid leaks.

Deep dive: Design Patterns, Explained Simply: Observer

Explanation

What interviewers look for

Decoupling benefit, real framework examples, and awareness of leaks and error handling.

Follow-up questions

  • How is Observer different from Pub/Sub?
  • How do you avoid memory leaks with observers?

More most-asked Design Patterns questions

← All Design Patterns questions