Behavioral PatternsObserver PatternMedium⏱️ ~2 min

Observer Pattern: Structure and Participants

Observer Pattern Structure
«interface»
Subject
+ attach(observer): void
+ detach(observer): void
+ notifyObservers(): void
ConcreteSubject
- observers: List<Observer>
- state: State
+ getState(): State
+ setState(s: State): void
◇ has many
«interface»
Observer
+ update(subject): void
ConcreteObserver
- observerState: State
- subject: ConcreteSubject
+ update(subject): void
Participants:

Subject (Interface or Abstract Class): Knows its observers and provides interface for attaching/detaching observer objects. May be an interface if no common implementation is needed, or abstract class if shared behavior exists across concrete subjects.

ConcreteSubject: Stores state of interest to observers. Sends notification to its observers when state changes. The notification typically happens in setter methods or after completing a business operation.

Observer (Interface): Defines an updating interface for objects that should be notified of changes. The update() method is the contract all observers must fulfill.

ConcreteObserver: Maintains a reference to a ConcreteSubject object. Stores state that should stay consistent with the subject's state. Implements the update() method to keep its state synchronized.

Collaboration Flow:
First, ConcreteSubject notifies its observers whenever a change occurs.
Second, each ConcreteObserver may query the subject for information to reconcile its state.
Third, the notification can trigger updates that cause further notifications (be careful of cycles).
Interview Tip: Discuss whether Subject should be an interface or abstract class. Use interface when subjects have no common implementation, but use abstract class when you can provide default attach(), detach(), and notifyObservers() logic.
💡 Key Takeaways
Subject maintains list of observers and notification logic
Observer interface defines update contract
ConcreteSubject stores state and triggers notifications
ConcreteObserver implements update to sync its state
Relationship is one-to-many with loose coupling
📌 Examples
1Subject interface with attach/detach/notify methods
2ConcreteSubject with state and observer list
3Observer interface with update method
← Back to Observer Pattern Overview