Design Patterns
Observer
Notifying everyone takes O(n) time — that grows with n, the number of subscribers.
The idea, in plain English
The observer pattern works like a newsletter. People subscribe, and whenever there's news, every subscriber gets notified automatically. The publisher doesn't need to know who the subscribers are. It just announces the news, and they all react.
How it works
- 1A 'subject' keeps a list of subscribers — functions it can call.
- 2Anyone interested subscribes by adding themselves to that list.
- 3When something happens, the subject calls every subscriber, so they all react.
When you'd use it
Use this when one change should update many things at once. Examples: a UI updating when data changes, notifications, or event systems.
Common beginner mistakes
- Don't forget to unsubscribe. Skipping this can cause memory leaks or updates from code that should be gone.
- Don't assume subscribers run in a guaranteed order.
Try it — edit and run
Click the code to edit · press ⌘/Ctrl+↵ to run
Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.
Expected output — hit Run to try it
Alice got: New article!
Bob got: New article!Not sure this is the right topic? See the learning paths → or where this leads →