Pattern Discussion and Comparison

We shall wind up the chapter in two parts. First, we shall consider the Iterator pattern in more detail, and second, we shall compare the Mediator and Observer patterns. Although all three patterns support communication between objects, C#'s language support for the Iterator has projected it into a different category than the other two. The Observer and Mediator still rely on communication via simple method calling.

Language Support for the Iterator Pattern

Fully 25 years ago, iterators were supported by languages such as Alphard and Clu and could be programmed via functions in Ada.[12] During the Java and C# 1.0 and 2.0 era, iterators consisted of the methods for the basic elements of a loop: Current, MoveNext, and Reset. If the programmer implemented these methods in a collection, a foreach loop would call them correctly for objects of that collection. C# 3.0's query expressions together with the IEnumerator interface have vastly simplified the handling of loops over arbitrary collections of data. Consider this excerpt from Example 9-2:

var selection = from n in daysInMonths
         where n.Key.Length > 5
         select n;

In earlier versions of C# iterators, both lambda expressions and delegates were used to express queries and interact with enumerator methods. Using lambda expressions, the selection would be expressed like this:

var selection = daysInMonths.
   Where(s => s.Key.Length>5);

The lambda expression is introduced by the Where keyword and reads like this: ...

Get C# 3.0 Design Patterns now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.