Possible flaw in Iterator pattern?

Viewed 70

Considering the following UML diagram: Iterator Pattern Image

If we add a method to addFriend() in Facebook class to add a new friend to a profile, the new friend doesn't reflect in the Facebook Iterator, and even if have a polling method in Facebook Iterator to check if any new friend has been added it would be a question of frequency and there can always be a corner case where the newly added friend didn't reflect.

I guess we can use Observer Pattern here but that would, in a way, imply that Iterator Pattern must always be used in conjunction with Observer Pattern.

I wanted to know if anyone thinks this is a legit issue, and how someone would go about tackling this

1 Answers

Your assessment is spot on. Concurrent modification is an important issue in iterators. The GoF book mentions it on page 261.

How robust is the iterator? It can be dangerous to modify an aggregate while you're traversing it. If elements are added or deleted from the aggregate, you might end up accessing an element twice or missing it completely. A simple solution is to copy the aggregate and traverse the copy, but that's too expensive to do in general.

A robust iterator ensures that insertions and removals won't interfere with traversal, and it does it without copying the aggregate. There are many ways to implement robust iterators. Most rely on registering the iterator with the aggregate. On insertion or removal, the aggregate either adjusts the internal state of iterators it has produced, or it maintains information internally to ensure proper traversal.

That sure sounds like the Observer pattern is one option. The GoF book goes on to reference a couple of research papers that have apparently studied this issue in more depth.

Related