Visitor Pattern
The Visitor pattern: adding operations over a fixed set of classes as separate visitor classes, how double dispatch finds the right method, and why a new element class is costly.
A set of classes that rarely changes, such as the shapes in a drawing or the nodes of a parsed program, often needs new operations: export them, total them, check them. Adding a method for each operation to every class scatters each operation across the classes. The Visitor pattern puts each operation in a class of its own, a visitor, with one method per element class.
This topic opens on that problem, then reads the participants off the class diagram and traces double dispatch call by call, the two method calls that pick the right code for both the element and the visitor. The template builds the pattern in three languages.
Two examples follow: totals and invoices over an order's line items, and Python's own ast.NodeVisitor, which counts the function calls in a program. A comparison shows functools.singledispatch and match doing the same work without an accept method. The gotcha is the cost the pattern moves rather than removes, a new element class, and the exercise asks whether a compiler should use a visitor.
By the end you can recognise a visitor, write one, and judge when its trade-off pays.
Contents
9 cardsnot started