chapter eleven

11 The Iterator and Visitor Design Patterns

 

This chapter covers

  • The Iterator Design Pattern
  • The Visitor Design Pattern

The two design patterns discussed in this chapter provide models for applications that must flexibly access data stored in various data structures such as lists, tuples, dictionaries, and trees. The example applications continue the theme of generating sports reports.

The Iterator Design Pattern enables a single algorithm to iterate over different sequential collections of objects without needing to know how the collections are implemented. Our first example application is modeled on this design pattern. The application’s algorithm can generate a report about the players on several baseball teams, even though each team stores its player data in a different type of sequential collection.

The Visitor Design Pattern works with a single data collection that contains different types of data. The collection is often structured as a tree. The pattern encapsulates different algorithms that are each designed to process the tree nodes. Our second example program is modeled on this design pattern. The application’s algorithms can generate different reports from the same collection of intramural games data.

A black text on a white background

AI-generated content may be incorrect.

11.1 The Iterator Design Pattern: One algorithm operates on different sequential data collections

11.1.1 Desired design features

11.1.2 Before using Iterator

11.1.3 After using Iterator

11.1.4 Iterator’s generic model

11.2 The Visitor Design Pattern: Different algorithms operate on a single data collection

11.2.1 Desired design features

11.2.2 Before using Visitor

11.2.3 After using Visitor

11.2.4 Visitor’s generic model

11.3 Choosing between Iterator and Visitor

Summary