数多くのItemを走査するため、Itemの配列をfor文で回すのも簡便な手だが、Iteratorパターンを用いると拡張性が高まる。例えば、後々配列ではなくベクターにしたい場合にMainをいじらなくてよくなる。更に、ConcreteIteratorはいくつ用意してもよく、例えば順方向だけでなく逆方向にも移動できるpreviousを有する実装を用意することも可能である。
Main.java
class Main {
public static void main(String[] args) {
int n=5;
ConcreteAggregate concreteAggregate = new ConcreteAggregate(n);
for(int i=0; i<n; ++i) concreteAggregate.append(new Item(i));
Iterator it = concreteAggregate.iterator();
while(it.hasNext()) {
Item item = (Item)it.next();
System.out.println(item.getNum());
}
}
}
Item.java
class Item {
private int num;
public Item(int num) {this.num=num;}
public int getNum() {return num;}
}
Aggregate.java
interface Aggregate {public abstract Iterator iterator();}
Iterator.java
interface Iterator {
public abstract boolean hasNext();
public abstract Object next();
}
ConcreteAggregate.java
class ConcreteAggregate implements Aggregate {
private Item[] items;
private int size=0;
public ConcreteAggregate(int maxSize) {this.items = new Item[maxSize];}
public void append(Item item) {this.items[size++] = item;}
public Item getItemAt(int idx) {return items[idx];}
public int getSize() {return size;}
public Iterator iterator() {return new ConcreteIterator(this);}
}
ConcreteIterator.java
class ConcreteIterator implements Iterator {
private ConcreteAggregate concreteAggregate;
private int idx;
public ConcreteIterator(ConcreteAggregate concreteAggregate) {
this.concreteAggregate = concreteAggregate;
this.idx = 0;
}
public boolean hasNext() {return (idx < concreteAggregate.getSize()) ? true : false;}
public Object next() {return concreteAggregate.getItemAt(idx++);}
}
$ javac Main.java Item.java Aggregate.java Iterator.java ConcreteAggregate.java ConcreteIterator.java && java Main
0
1
2
3
4