RecapDifficulty: Advanced1 min

Recap: Visitor Pattern

Operations become classes, double dispatch picks the method, and new element types cost the most.

Visitor puts each operation over a set of classes into a class of its own.

  • Intent. Add operations over element classes without changing those classes.
  • Participants. A visitor interface with one method per element class, concrete visitors with one operation each, and elements whose accept calls the method for their own class.
  • Double dispatch. accept chooses by the element's class; the visit call inside it chooses by the visitor's class.
  • In Python. ast.NodeVisitor finds the method by name, visit_ plus the class name; singledispatch and match need no accept at all.
  • The trade-off. A new operation is one class; a new element class edits every visitor.
  • When not. Element classes that change often, or only one or two operations.