The Visitor pattern separates algorithms from a heterogeneous object structure. It suits a tree such as intramural sports data, where multiple passes produce different reports without embedding report logic in the nodes. section 11.0 section 11.2
A typical implementation divides responsibilities:
- Make each element implement Node.accept(visitor). Intramural and Sport accept a visitor and forward it to their children; Game and Hall dispatch directly. section 11.2.3
- Define a Visitor interface with a visit method for every element type, such as visit_intramural(), visit_sport(), visit_game(), and visit_hall(). section 11.2.3 section 11.2.4
- Put each operation in a concrete visitor. ScoresReportVisitor, ActivitiesReportVisitor, and WinningsReportVisitor each implement one reporting algorithm. section 11.2.3
- Run a pass by sending a visitor to the root: intramural_node.accept(visitor). Polymorphism selects the visit method matching each node type. section 11.2.3 section 11.2.4
Refactoring intramural reports
Before Visitor, Intramural, Sport, Game, and Hall contain methods for scores, activities, and winnings reports. Adding another report requires changing those data classes and extending their call chains. After refactoring, the classes maintain the tree and expose properties, while separate visitors generate each report. The same tree can therefore produce scores, activity counts, and winnings through three independent passes. section 11.2.2 section 11.2.3 section 11.4
Figure 11.11 The generic model of the Visitor Design Pattern. Compare with figure 11.10. Each Visitor class encapsulates an algorithm. To execute an algorithm during a pass of the Element objects, each Element object accepts a Visitor object. The accept() function of each concrete Element object calls the visit method that corresponds to that Element object. The visit methods together execute the Visitor class’s algorithm as they visit the Element objects one after another.
Use the generic model to trace how concrete elements accept one visitor and dispatch to matching visit methods during a pass. section 11.2.4



