samedi 9 novembre 2019

How to implement a cursor iterator?

In the "Structure" section of the Iterator design pattern, the book Design Patterns: Elements of Reusable Object-Oriented Software defines the Iterator class with four basic operations: First, Next, IsDone and CurrentItem.

In the "Implementation" section, the book contains the following item:

  1. Who defines the traversal algorithm? The iterator is not the only place where the traversal algorithm can be defined. The aggregate might define the traversal algorithm and use the iterator to store just the state of the iteration. We call this kind of iterator a cursor, since it merely points to the current position in the aggregate. A client will invoke the Next operation on the aggregate with the cursor as an argument, and the Next operation will change the state of the cursor.

    If the iterator is responsible for the traversal algorithm, then it’s easy to use different iteration algorithms on the same aggregate, and it can also be easier to reuse the same algorithm on different aggregates. On the other hand, the traversal algorithm might need to access the private variables of the aggregate. If so, putting the traversal algorithm in the iterator violates the encapsulation of the aggregate.

But no example implementation of a cursor iterator is given. Should the First, IsDone and CurrentItem operations be defined on the cursor iterator or on the aggregate (and consequently be also invoked with the cursor as an argument)? Please provide an example implementation.

Aucun commentaire:

Enregistrer un commentaire