Iterator, Mediator, and Memento Patterns (GoF Behavioral Patterns)
This page covers the tail end of the Iterator pattern (internal iterators, known uses, and related patterns), the complete Mediator pattern, and most of the Memento pattern. These are behavioral patterns from the Gang of Four catalog concerned with managing object communication, state capture, and traversal.
Key Concepts
Iterator (conclusion)
Internal iterators can encapsulate different iteration strategies (e.g., FilteringListTraverser adds a TestItem predicate to control which elements are processed)
Internal iterator Traverse uses Template Method — TestItem and ProcessItem are primitive operations overridden by subclasses
Smalltalk collections use do: with blocks (closures) as internal iterators; ReadStream serves as an external iterator for sequential collections
No standard external iterators exist for non-sequential Smalltalk collections (Set, Dictionary)
Mediator
Intent: Define an object that encapsulates how a set of objects interact; promotes loose coupling by preventing direct references between colleagues
Replaces many-to-many interactions with one-to-many (mediator-to-colleagues), which are easier to understand and maintain
Colleagues only know the mediator, not each other — all communication routes through the mediator
Trades interaction complexity for mediator complexity — the mediator can become a monolith
The abstract Mediator class can be omitted when colleagues only work with one mediator
Colleague-Mediator communication can use Observer pattern (colleagues as Subjects) or a specialized notification interface where the colleague passes itself as an argument
Memento
Intent: Capture and externalize an object's internal state without violating encapsulation, so the object can be restored later
Also known as Token
Three participants: Originator (creates/restores from memento), Memento (stores state), Caretaker (safekeeps memento without examining contents)
Memento has two interfaces: narrow (public, for caretaker — pass-through only) and wide (private, for originator — full state access)
Mementos are passive — only the originator assigns or retrieves state
Incremental mementos: when created in predictable sequence, can store only the delta rather than full state