Iterator: Around and Around
Iterator Players
The Iterator pattern features these two players:
- Aggregate — A whole that is composed of many parts; a component source.
- Iterator — An object that supplies elements of the Aggregate one at a time. Iterators may return Aggregate elements in different orders or perform filtering on what elements are returned.
An External Iterator is a free-standing instance supplied
by an Aggregate that provides Aggregate elements in some order.
A new External Iterator instance is created by a Creation or Factory Method
on the Aggregate. Each Iterator instance remembers its Aggregate,
and keeps track of its current position.
Internal Iterators use Callbacks to allow the Aggregate
itself to supply objects to a Consumer object in a manner
of the Aggregate's choosing.
Internal Iterators supply iterator methods that call a user-supplied
Consumer objects back.The Aggregate method will push elements, one at a time,
back to the Consumer, kind of like this:
bunch.forEach(new Consumer() {
public void consume(Object item) {
System.out.println(item);
}
});
Iterators can be composed, and filter the results
of other Iterators.
The code below shows an Iterator that decorates or wraps
another Iterator that supplies Integers
,
and returns only the even Integers
.
package com.industriallogic.example;import java.util.Iterator;public class EvenFilteringIterator implements Iterator { private Integer next;
private Iterator source; public EvenFilteringIterator(Iterator source) {
this.source = source;
} private boolean isEven(int i) {
return (i % 2) == 0;
} public boolean hasNext() {
while (source.hasNext()) {
next = (Integer) source.next();
if (isEven(next))
return true;
}
return false;
} public Object next() {
return next;
} public void remove() {
}
}
(Reading...)
Formatting Hints:
To format... | use this markup: |
---|---|
source code | {source:lang=java|lineNumbers=false}...{source} (Supported languages: java, cpp, csharp, c, python.) |
bold text | __some text__ |
italicized text | ~~some text~~ |
underlined text | @@some text@@ |
a method or class name | ``myMethod(...)`` |