Visitor pattern
hard 55 minVisitor moves an operation on a family of classes into an object of its own.
Video lesson · Chapter 1 of 6
Make a prediction
See it run
Two calls, two types: the element says what it is, the visitor does the work.
Operations
Export to HTML
A document of three parts and one visitor. Follow the two calls per part.
Step 1 of 8
The visitor arrives
The document got an empty HtmlExport.
Step 1: The visitor arrives
class Document: def accept(self, v): for e in self._elements: e.accept(v)class Paragraph: def accept(self, v): v.visit_paragraph(self)class HtmlExport: def visit_paragraph(self, p): self._out.append(f"<p>{escape(p.text)}</p>")- Watch
- accept, visit
- Result
- Three tags
Nobody asks for a type.
In the real world
The same visitor pattern doing real jobs. Pick one and step through it.
A walker leads a visitor through a small document.
Step 1 of 4
Enter doc
The path is doc.
Step 1: Enter doc
Common mistakes
The bugs interviewers watch for, with the fix beside each.
A copied accept
criticalImages are exported as paragraphs.
Wrongclass Image: def accept(self, v): v.visit_paragraph(self)Rightclass Image: def accept(self, v): v.visit_image(self)accept in the base class
majorWith overloads the base type is chosen.
Wrongabstract class Element { void accept(Visitor v) { v.visit(this); }}Rightclass Image extends Element { void accept(Visitor v) { v.visit(this); }}A reused visitor
majorThe old result is still inside.
Wronghtml = HtmlExport()for doc in docs: doc.accept(html)Rightfor doc in docs: html = HtmlExport() doc.accept(html)A silent default
criticalNew elements vanish from the export.
Wrongdef visit_default(self, e): passRightdef visit_default(self, e): raise NotImplementedError(type(e))Text without escaping
criticalA script in a paragraph runs.
Wrongout.append(f"<p>{p.text}</p>")Rightout.append(f"<p>{escape(p.text)}</p>")Type checks inside a visitor
majorThe question the pattern removed is back.
Wrongdef visit(self, e): if isinstance(e, Image): ...Rightdef visit_image(self, i): ...
Interview tips
Draw the grid
- Types down.
- Operations across.
- Which side grows?
Two handshakes
- accept: I am an image.
- visit: I am HTML.
- No type checks.
Mind the state
- Collecting: one per run.
- Returning: share freely.
- Elements immutable.
Know the neighbours
- Sealed and switch.
- Methods in classes.
- singledispatch.