Observer pattern
Наблюдатель
A behavioral design pattern that lets objects or functions subscribe to changes or events from a source. The source notifies its subscribers without needing to know how each one will respond.
Also known as: pub/sub, observer
What the Observer pattern solves
Say a document editor needs to update a word counter and a save indicator whenever the text changes. The document could call both pieces of UI directly, but then adding another feature would mean editing the document code. With Observer, each feature registers for updates. The document announces that the text changed, and each registered listener decides what to do about it.
How it works
The source, often called the subject, keeps a collection of observers. An observer can be an object with an update method or just a callback that follows an agreed signature. When something changes, the subject calls the registered observers. It can pass the new value in the notification, or it can just signal that something changed and let observers read the state themselves. An unsubscribe operation lets an observer stop receiving updates.
Example in Python
class Document:
def __init__(self):
self.text = ""
self._listeners = []
def subscribe(self, listener):
self._listeners.append(listener)
def unsubscribe(self, listener):
self._listeners.remove(listener)
def replace_text(self, text):
self.text = text
for listener in tuple(self._listeners):
listener(text)
def show_word_count(text):
print(len(text.split()))
doc = Document()
doc.subscribe(show_word_count)
doc.replace_text("Hello world") # 2
doc.unsubscribe(show_word_count)
The tuple captures the listeners registered when notification begins. A listener added during a callback won't receive that update; one removed during a callback may still receive it. This example notifies on every call to replace_text, even if the text hasn't changed. An implementation that promises change-only notifications would check the old value first.
Where it fits and what can go wrong
UI event listeners and application state subscriptions are familiar uses. A common bug is leaving a screen subscribed after it closes: the source can keep the callback, and anything it references, alive. Tie cleanup to the lifetime of the subscriber.
In this example, the callbacks run synchronously. A slow callback delays the caller, and an exception stops the loop before later callbacks run. Observer doesn't inherently require synchronous delivery, and it doesn't promise a particular ordering or error policy. Those are decisions the implementation needs to make.
Interview questions
Be ready to distinguish classic Observer from brokered pub/sub. In Observer, the subject usually holds references to its observers and notifies them directly. With brokered pub/sub, publishers send messages to a topic and the intermediary tracks the subscriptions. The terms are sometimes used loosely, so explain who holds the subscriptions rather than relying on the label. If asked to implement the pattern, clarify what happens when a listener subscribes twice, unsubscribes during dispatch, or changes the subject again from inside a callback.