Expression Problem and the Visitor Pattern

I have a few issues understanding the code in Subsection 8.11.2: The Visitor Pattern of the lecture notes.

  1. In the visitor example, what is the interface Expr that classes Const, Var and Add implement?

  2. Why does the interface Exp not contain the methods eval, toString and toXML anymore? + Why is it there when it’s not being implemented by any class?

  3. In the main function, I don’t quite get how e.accept(new XMLFormatter()); is able to call the right method.

The interface is given in the code:

public interface Exp {
    <T> T accept(ExprVisitor<T> v);
}

It says: Every expression should have an accept method as a docking point for visitors.

The whole point of the visitor pattern is to move the functionality out:
Instead of every expression itself having to handle stuff like eval, we have one evaluator that visits each expression and evaluates it.
One calls the accept method with the wanted visitor and the visitor can then perform its functionality on the expression it is called on.

Therefore, we have only one accept interface in the expressions and have multiple visitors like a XMLFormatter visitor that performs the previous toXML functionality, a ToStringVisitor (or maybe one would call it Formatter) for toString, and an Evaluator a visitor for eval.

Draw the trace and take a look at the overwriting / overloading rules:
The expression accepts a visitor.
As previously with toXML, the accept method of this expression class is called with the XMLFormatter as visitor argument.
The accept method is implemented such that it invokes the visitor on itself.
Therefore, we go the correct overloaded visit method in the XMLFormatter for the expression we called it on.
The same scheme continues for the subexpressions as we visit them recursively with the accept calls in the visitor.

1 Like

Thanks for the Question and the Discussion. I will however fix the notation that is a bit in consistent at the moment.

1 Like