1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| interface Iterator { boolean hasNext();
Object next(); }
interface Container { Iterator getIterator(); }
class NameRepository implements Container { public String[] names = {"Robert", "John", "Julie", "Lora"};
@Override public Iterator getIterator() { return new NameIterator(); }
private class NameIterator implements Iterator {
int index;
@Override public boolean hasNext() { return index < names.length; }
@Override public Object next() { if (this.hasNext()) { return names[index++]; } return null; } } }
public class IteratorPatternDemo { public static void main(String[] args) { NameRepository namesRepository = new NameRepository(); for (Iterator iter = namesRepository.getIterator(); iter.hasNext(); ) { String name = (String) iter.next(); System.out.println("Name : " + name); } } }
|