Mediator, Memento & Visitor
Three remaining GoF behavioural patterns — Mediator centralises communication between components, Memento captures and restores state, and Visitor adds operations to object structures without changing them. Plus brief notes on Interpreter.
Mediator
Intent: define an object that encapsulates how a set of objects interact. Components talk to the mediator instead of to each other, reducing a many-to-many web of dependencies to many-to-one.
Every form widget knows the others: the "country" dropdown updates the "state" dropdown, which enables the "zip" field, which validates the "submit" button… N widgets → up to N² links.
Widgets only notify the mediator ("I changed"). The form dialog mediator holds all the interaction rules in one place. Widgets become reusable.
interface Mediator { notify(sender: Widget, event: string): void; }
class CheckoutForm implements Mediator {
constructor(private country: Select, private state: Select, private zip: Input, private submit: Button) {
[country, state, zip, submit].forEach((w) => (w.mediator = this));
}
notify(sender: Widget, event: string) {
if (sender === this.country && event === "change") {
this.state.setOptions(statesFor(this.country.value));
this.zip.setPattern(zipPatternFor(this.country.value));
}
this.submit.enabled = this.country.value !== "" && this.zip.valid;
}
}Real examples: air-traffic control (planes talk to the tower, not each other), chat rooms, UI dialog controllers, MediatR in .NET, message brokers at the system level, Redux stores (components dispatch actions to one place).
Memento
Intent: without violating encapsulation, capture an object's internal state so it can be restored later.
Roles: the originator (the object whose state is saved) creates a memento (an opaque snapshot); a caretaker (history manager) stores mementos but never looks inside them.
public final class Editor { // originator
private String text = ""; private int cursor;
public void type(String s) { text = text.substring(0, cursor) + s + text.substring(cursor); cursor += s.length(); }
public Memento save() { return new Memento(text, cursor); }
public void restore(Memento m) { this.text = m.text; this.cursor = m.cursor; }
// Opaque snapshot: fields are private to Editor's nested class
public static final class Memento {
private final String text; private final int cursor;
private Memento(String text, int cursor) { this.text = text; this.cursor = cursor; }
}
}
class History { // caretaker
private final Deque<Editor.Memento> stack = new ArrayDeque<>();
void push(Editor.Memento m) { stack.push(m); }
Editor.Memento pop() { return stack.pop(); }
}
editor.type("Hello");
history.push(editor.save());
editor.type(" world");
editor.restore(history.pop()); // back to "Hello"from dataclasses import dataclass
@dataclass(frozen=True)
class EditorMemento: # immutable snapshot
text: str
cursor: int
class Editor:
def __init__(self): self.text, self.cursor = "", 0
def type(self, s):
self.text = self.text[:self.cursor] + s + self.text[self.cursor:]
self.cursor += len(s)
def save(self) -> EditorMemento:
return EditorMemento(self.text, self.cursor)
def restore(self, m: EditorMemento):
self.text, self.cursor = m.text, m.cursorclass Editor {
private text = ""; private cursor = 0;
type(s: string) { this.text = this.text.slice(0, this.cursor) + s + this.text.slice(this.cursor); this.cursor += s.length; }
save() { return Object.freeze({ text: this.text, cursor: this.cursor }); }
restore(m: ReturnType<Editor["save"]>) { this.text = m.text; this.cursor = m.cursor; }
}Used for: undo (snapshot-based, vs the Command pattern's inverse operations), transaction rollback, game save points, "discard changes" in forms. With immutable state (Redux, persistent data structures), every previous state is already a memento — time-travel debugging is nearly free. Watch memory: snapshot large objects incrementally or cap history.
Visitor
Intent: represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements.
The problem: you have a stable set of node types (an AST: Number, Add, Multiply, Variable) and keep adding operations: evaluate, pretty-print, type-check, optimise, compile. Putting every operation into every node class bloats them and mixes concerns.
Visitor moves each operation into its own class with one method per node type. Each node implements accept(visitor), which calls the right visit method — double dispatch: the method chosen depends on both the node's type and the visitor's type.
interface Expr { <R> R accept(Visitor<R> v); }
record Num(double value) implements Expr { public <R> R accept(Visitor<R> v) { return v.visitNum(this); } }
record Add(Expr l, Expr r) implements Expr { public <R> R accept(Visitor<R> v) { return v.visitAdd(this); } }
record Mul(Expr l, Expr r) implements Expr { public <R> R accept(Visitor<R> v) { return v.visitMul(this); } }
interface Visitor<R> { R visitNum(Num n); R visitAdd(Add a); R visitMul(Mul m); }
class Evaluator implements Visitor<Double> {
public Double visitNum(Num n) { return n.value(); }
public Double visitAdd(Add a) { return a.l().accept(this) + a.r().accept(this); }
public Double visitMul(Mul m) { return m.l().accept(this) * m.r().accept(this); }
}
class Printer implements Visitor<String> {
public String visitNum(Num n) { return String.valueOf(n.value()); }
public String visitAdd(Add a) { return "(" + a.l().accept(this) + " + " + a.r().accept(this) + ")"; }
public String visitMul(Mul m) { return a(m.l()) + " * " + a(m.r()); }
private String a(Expr e) { return e.accept(this); }
}
// Modern Java alternative: sealed interfaces + pattern matching (no accept() needed)
sealed interface E permits N, A {}
record N(double v) implements E {}
record A(E l, E r) implements E {}
static double eval(E e) {
return switch (e) {
case N n -> n.v();
case A a -> eval(a.l()) + eval(a.r());
}; // compiler checks exhaustiveness
}# Python: functools.singledispatch gives visitor-style dispatch on type
from dataclasses import dataclass
from functools import singledispatch
@dataclass
class Num: value: float
@dataclass
class Add: left: object; right: object
@dataclass
class Mul: left: object; right: object
@singledispatch
def evaluate(node): raise TypeError(node)
@evaluate.register
def _(node: Num): return node.value
@evaluate.register
def _(node: Add): return evaluate(node.left) + evaluate(node.right)
@evaluate.register
def _(node: Mul): return evaluate(node.left) * evaluate(node.right)
# Or structural pattern matching (3.10+)
def show(node) -> str:
match node:
case Num(v): return str(v)
case Add(l, r): return f"({show(l)} + {show(r)})"
case Mul(l, r): return f"{show(l)} * {show(r)}"
# The stdlib's ast.NodeVisitor is a classic Visitor: def visit_FunctionDef(self, node): ...// TS: discriminated unions + exhaustive switch replace classic Visitor
type Expr =
| { kind: "num"; value: number }
| { kind: "add"; l: Expr; r: Expr }
| { kind: "mul"; l: Expr; r: Expr };
function evaluate(e: Expr): number {
switch (e.kind) {
case "num": return e.value;
case "add": return evaluate(e.l) + evaluate(e.r);
case "mul": return evaluate(e.l) * evaluate(e.r);
default: { const never: never = e; return never; } // compile error if a case is missing
}
}
// Babel and ESLint plugins use visitor objects: { Identifier(path) {...}, CallExpression(path) {...} }The expression problem
| Add a new operation | Add a new node type | |
|---|---|---|
| Methods on node classes (OOP) | Edit every class | Easy: one new class |
| Visitor / pattern matching | Easy: one new visitor/function | Edit every visitor |
Use Visitor when node types are stable and operations grow — compilers, linters, document exporters. Modern languages' sealed types and pattern matching give the same benefit with less ceremony.
Interpreter (briefly)
Intent: define a grammar's representation and an interpreter that evaluates sentences in it. In practice: represent expressions as a Composite tree (an AST) and evaluate recursively — exactly the expression example above. Used for small DSLs: rule engines, query filters, template languages, regular expressions. For anything bigger, use a parser generator and see the Compilers track.
- Mediator centralises interactions among components; beware a god-object mediator.
- Memento captures opaque snapshots for undo/rollback; immutable state makes it trivial.
- Visitor adds operations to a stable class hierarchy via double dispatch.
- Pattern matching over sealed/union types is the modern visitor.
- Interpreter = AST (composite) + recursive evaluation, for small DSLs.