Java EE 8 Design Patterns and Best Practices
上QQ阅读APP看书,第一时间看更新

Explaining Iterator

Imagine that we want a way to access elements of an aggregate object sequentially without exposing its internal structure. The Iterator pattern does just that.

The Iterator pattern is responsible for sequentially accessing the aggregate object and defining an interface to access the elements without exposing the internal structure. This interface doesn't put a new element on the aggregate object, but simply reads elements to it. In the following diagram, you can see the structure of an Iterator and how it is designed:

In the preceding diagram, we can see the Aggregate and Iterator interfaces with their concrete subclasses. The client is the class that uses the Iterator to access elements of Aggregate.

This pattern is used on Java collections such as list, deque, and set. Understanding this pattern will help you to understand Java collections.