The Visitor Design Pattern separates operations from the objects they process. It suits a single heterogeneous collection, especially a tree, when several algorithms must make repeated passes over the same nodes. section 11.0 section 11.2
A typical implementation divides responsibility into two interfaces and their concrete classes:
- Node defines accept(Visitor&); Intramural, Sport, Game, and Hall implement it and forward control to the matching visitor method. section 11.3
- Visitor declares visit_Intramural(), visit_Sport(), visit_Game(), and visit_Hall() methods for each node type. section 11.3
- Concrete visitors encapsulate separate algorithms, such as ScoresReportVisitor, ActivitiesReportVisitor, and WinningsReportVisitor. section 11.3
Intramural sports reports
A tree contains an Intramural root, sports, games, and residence halls. One pass prints scores, another counts games by sport, and another prints each hall’s wins. The pre-pattern design places report methods throughout the data classes, creating a call chain. Refactoring moves each report into its own visitor; the client then calls intramural_node->accept(visitor) for each report. section 11.2 section 11.2.2
Figure 11.9 The generic model of the Visitor Design Pattern. Compare it with figure 11.8. 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 member function that corresponds to that Element object. The visit member functions together execute the Visitor class’s algorithm as they visit the Element objects one after another.
The generic model shows how concrete elements accept a visitor and dispatch to the visit method matching each element type. section 11.3.1
The pattern makes algorithms loosely coupled to the data collection and to one another. New report algorithms can be added as visitors without modifying the existing tree classes. section 11.4



