Mediator & Iterator
You'll learn to
- -Explain Mediator as a control tower that replaces many-to-many direct links, and count the links saved
- -Explain Iterator as "give me the next item" without exposing how the collection is stored
- -See how a second iterator changes the traversal order without touching the calling code
Mediator and Iterator are two behavioral patterns that come up often in LLD rounds. Mediator turns a tangle of objects talking to each other into a hub with spokes. Iterator gives you a uniform way to walk through a collection without knowing how it is stored.
Mediator: Replacing a Web of Direct References
Think of an airport. Pilots do not radio every other pilot in the sky. Every plane talks to the control tower, and the tower tells each plane what it needs to know. Without the tower, every plane would need a direct line to every other plane, and each new plane would have to be added to everyone's list.
A chat room has the same problem. If every User holds a reference to every other User, then with n users there are n × (n - 1) / 2 links to maintain. A mediator needs only one link per user.
The demo shows the mediator version. Each user knows only the chat room, and the chat room routes each message to everyone except the sender.
A new user is one registration call. The trade-off to name out loud is that the mediator can turn into a "god object", one class that knows too much. Keep its job to routing and coordination, not business rules.
Iterator: Traversal Without Exposing Internals
When you press "next channel" on a TV remote, you do not care how the channels are stored. You just want the next one. An iterator gives a collection that same "next item" interface. Most languages build it in, but the pattern matters in interviews because custom collections, such as a tree or pages fetched from an API, often need their own iterator.
The demo walks a small tree with a depth-first iterator, which goes as deep as it can before moving sideways, and then with a breadth-first iterator, which visits the tree level by level. The loop that uses them is identical.
The value of a custom iterator: the traversal strategy is swappable. A breadth-first iterator with the same interface lets callers change the order without changing a line of the code that uses it.
Interview Signal is part of Pro
See a real weak answer next to a real strong one for this exact topic.
Quiz is part of Pro
Test what you just read with a short quiz, and bank the XP.
Discussion0
Join the Discussion
Sign in to leave comments, reply to others, or like insights.
No comments yet. Be the first to start the thread!