Chapter 9. Behavioral Patterns: Iterator, Mediator, and Observer
The three behavioral patterns we will study in this chapter support communication between objects while letting them keep their independence and, in some cases, their anonymity. The Iterator pattern is a fundamental pattern that has wide application in many situations and is substantially supported by C# 3.0’s LINQ or Linq (Language INtegrated Query) extensions. The Mediator and Observer patterns mirror the mailbox and publish/subscribe methodologies that are well-known in distributed systems.
The Iterator pattern provides a way of accessing elements of a collection sequentially, without knowing how the collection is structured. As an extension, the pattern allows for filtering elements in a variety of ways as they are generated.
Consider a typical file directory such as that shown in Figure 9-1. Common directory operations include searching for files with particular names or extensions, or files created before or after certain dates. When searching for a file, the directory structure is unimportant and should be abstracted away. For directories of reasonable size, another useful operation is to list their contents in a hierarchy, as shown in Figure 9-2. The loop that displays a directory in a neat format can once again be independent of which item is supplied next. As long as enough is known about each item’s position in the hierarchy and its attributes (such as size), a loop should be ...