How does the Observer pattern work, and where is it used?
MediumConceptDesign Patterns
Answer
In the Observer pattern, a subject keeps a list of observers and notifies all of them when its state changes, so observers react without the subject knowing their concrete types. It defines a one-to-many dependency between objects.
- Structure: the subject exposes
subscribe(),unsubscribe()andnotify(); each observer implements anupdate()method. - Examples: UI event listeners, a stock price feed updating several displays, and a channel notifying its subscribers about a new video.
- Push vs pull: the subject can send the changed data with the notification, or observers can query the subject after being notified.
- Pitfalls: observers that never unsubscribe cause memory leaks, and slow observers delay others unless notification is asynchronous. At system scale, the same idea becomes publish-subscribe messaging.
More in Design Patterns
| # | Problem | Platform | Difficulty | Open | 1st1st Visit | 2nd2nd Visit | RevRevise |
|---|---|---|---|---|---|---|---|
| 1 | What is the Singleton pattern, and what are its drawbacks? | Concept | Easy | Read the answer to What is the Singleton pattern, and what are its drawbacks? | |||
| 2 | What is the Factory pattern, and when would you use it? | Concept | Medium | Read the answer to What is the Factory pattern, and when would you use it? | |||
| 3 | How does the Observer pattern work, and where is it used? | Concept | Medium | Read the answer to How does the Observer pattern work, and where is it used? | |||
| 4 | What is the Strategy pattern, and how does it differ from the State pattern? | Concept | Medium | Read the answer to What is the Strategy pattern, and how does it differ from the State pattern? |