Apparently this pattern is a misnomer of double dispatch (see Double Dispatch) for languages that do not natively support it.

Note

This is a pattern that separates operations from the objects they act upon.
The point of the visitor is to factor out operations from a class hierarchy to a single interface (the visitor). The visitor interface in the interface should be implemented in different ways for the different operations.

Whats the Point?

As I understand it, if we have an abstract class that has multiple implementations, and we want to add functionality to all these classes, we would have to update the entire class hierarchy (add the interface to the abstract class and then implement it with polymorphism). This could be annoying over time as well add more implementations and operations. Instead, we can add a single interface in the abstract class that accepts the visitor class (accept) which calls the appropriate visitX method. This is the double dispatch part. The visitor class has one method per implementation of the abstract class. We pass these visitX methods to the implementations of the abstract class like implementations.accept().

This is a pretty good explanation.

Method for Answering Visitor Problems

  1. Identify the two class hierarchies:
    • Data: e.g., the AST classes
    • Operations: e.g., the visitors (that act on the Data)
  2. Start the object diagram:
    • Draw the heap as it looks in the main method.
    • Draw the statics frame (if there is one).
    • Draw the main stack frame.
    • Connect the main frame and the statics frame to the heap objects.
  3. Find the line of code where program execution will be paused at for us to draw the object diagram. In ece222 terms, where the Program Counter (pc) will be. This should be marked somehow, perhaps with a comment that says HERE.
  4. Look at the main method. Figure out which line in the main method will eventually lead to the pc line. For this you will need to think holistically: there should be enough clues around the program for you to figure it out. This is the most challenging part
  5. Draw the next stack frame on your object diagram, what is main calling? Repeat until you get to the frame with the pc line.