AlgoViz

Visitor pattern

hard 55 min

Visitor moves an operation on a family of classes into an object of its own.

Watch lesson4:34

Where it shows up

The same pattern appears across everyday software.

  • Python ast

    `ast.NodeVisitor` calls `visit_` plus the class name, or `generic_visit`. `NodeTransformer` rewrites the tree.

  • Clang

    `RecursiveASTVisitor` walks the syntax tree of C++. The documentation builds a tool by overriding one Visit method.

  • Java FileVisitor

    `Files.walkFileTree` calls `preVisitDirectory`, `visitFile` and `postVisitDirectory`. The answer may skip or terminate.

  • Java annotation processing

    `ElementVisitor` in `javax.lang.model` visits packages, types and methods, with `visitUnknown` for what comes later.

  • ANTLR

    Generates listeners and visitors for a grammar. In a visitor you walk the children yourself.

  • Babel

    Plugins are objects with methods per node type, called by `@babel/traverse`.

  • Roslyn

    The C# compiler platform offers `CSharpSyntaxWalker` with a Visit method per syntax node.

  • ASM

    `ClassVisitor` reads and writes Java bytecode. Its documentation fixes the order in which the visit methods are called.

  • C++ std::visit

    Calls a callable with the value that a `std::variant` currently holds.

  • ESLint

    A rule returns an object with a method per node type. The linter walks once and calls all rules.

  • graphql-js

    `visit` with enter and leave, and `visitInParallel` for several visitors in one walk.