Monday, December 29, 2014

Iterator Pattern

The Iterator Pattern provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation.

Once you have a uniform way of accessing the elements of your aggregate (collection) objects, you can write polymorphic code that works with any of these aggregates.

The other important impact on your design is that the Iterator Pattern takes the responsibility of traversing elements and gives that responsibility to Iterator object, and not the aggregate object. This keeps the aggregate interface and implementation simpler. It removes the responsibility for iteration from the aggregate and keeps the aggregate focused on the things it should be focused on.

The core principle behind this pattern is Single Responsibility Principle, which states that "A class should have only one reason to change".

Every responsibility of a class is an area of potential change. More than one responsibility means more than one area of change. So this principle guides us to keep each class to a single responsibility.

Java language provides the iterator interface (java.util.iterator) and all collection objects in Java already implement this interface.

No comments:

Post a Comment