Thursday, October 15, 2015

Design Pattern - Iterator pattern

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

This simplifies aggregate interface and implementation by placing traversal responsibility on iterator and this traversal of a collection is promoted to a full object comparing to a logic embedded in the aggregate.  In the process helping the client of aggregate object a polymorphic traversal.

In short - "Sequentially access the elements of a collection"


How to use Iterator pattern:
1. Two types of objects needed, one is called 'aggregate', other is called 'iterator'

2. "Aggregate" abstraction should have a method (i.e. createIterator) to create corresponding iterator

3. Each derived concrete class of aggregate base class has to provide implementation of the abstract method (i.e. createIterator)

4. Create abstract "iterator" base which can have method like next, hasNext, remove. See Note-3 and 4 to know more 

5. Each derived concrete class of "iterator" base class should provide implementation of methods described in the "iterator".

6. The client will create necessary aggregate object based on collection structure and ask for "iterator" from the aggregate object which will return a concrete iterator as generic type. 



Class diagram:





















Benefit:
1. Aggregate object can have it's encapsulation intact without exposing how the collection structure is defined
2. Allows the client to traverse different ways
3. Supports multiple simultaneous traversal on a collection
4. Provides uniform interface to traverse heterogeneous collections


Notes:

1. Internal Iterator vs External Iterator - java.util.Iterator is an external iterator as client has to control the iteration. Internal iterator is controlled by the iterator itself and client has to inform the iterator needs to be done as it iterator through.

2. Robust Iterator - the iterator can provide both insertion and deletion during traversal and doesn't make a copy of the aggregate. This iterator makes sure the element(s) not fetched twice or skipped due to insert or delete in the collection. 

3. java provides java.util.Iterator which can be used in most of the cases. This interface has three methods (next, hasNext, remove). If derived concrete Iterator doesn't need to support for remove method, java.lang.UnsupportedOperationException can be thrown.

4. An Iterator can be defined to move backwards as well forwards. Java provides such interface java.util.ListIterator with next, hasNext, previous, hasPrevious, remove methods along with other like (nextIndex, previousIndex, set, add).

Things to check back:
1. How to write a thread safe, robust Iterator


Resources:
1. Head First Design Pattern
2. https://sourcemaking.com/design_patterns
3. https://en.wikipedia.org/wiki/Iterator_pattern 

No comments: