11 The Iterator and Visitor Design Patterns

 

This chapter covers

  • The Iterator Design Pattern
  • The Visitor Design Pattern

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

The Iterator Design Pattern enables a single algorithm to iterate over multiple sequential collections of objects without needing to know how the collections are implemented. Our first example application is modeled from 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 form 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, each designed to process the tree nodes. Our second example program is modeled from this design pattern. The application’s algorithms can generate different reports from the same collection of intramural games data.

NOTE

Be sure to read the introduction to part 4 for important information about design patterns in general and to learn how this and subsequent chapters teach each pattern.

11.1 The Iterator Design Pattern encapsulates iterating over different sequential collections

11.1.1 Desired design features

11.1.2 Before using the Iterator Design Pattern

11.1.3 After using the Iterator Design Pattern

11.1.4 Iterator’s generic model

11.2 The Visitor Design Pattern encapsulates different algorithms that operate on a data collection

11.2.1 Desired design features

11.2.2 Before using the Visitor Design Pattern

11.3 After using the Visitor Design Pattern

11.3.1 Visitor’s generic model

Summary