Comparison
Double dispatchvsVisitor pattern
Double dispatch
the method that runs depends on the runtime types of two objects, and one call was not enough to get there.
Selecting behaviour on the runtime types of two participants rather than one, which single-dispatch languages cannot do directly. The visitor pattern is the standard workaround: the element calls a method on the visitor named for its own type, so two virtual calls together do what one could not. Knowing the mechanism is what makes the visitor's odd accept-and-call-back shape stop looking arbitrary.
Full entry →Visitor pattern
you added a new operation over the whole tree by writing one class, and did not touch any of the node types.
Moving an operation out of a structure's element classes into a separate object, which each element calls back with its own type. It trades one kind of extensibility for another: adding an operation becomes easy and adding a node type becomes a change to every visitor — the expression problem, stated concretely. It is genuinely used in compilers, linters and anything that walks an AST, and almost nowhere else.
Full entry →