interface Iterator {
public Object first();
public Object next();
public boolean isDone();
public Object currentItem();
}
class ConcreteIterator implements Iterator {
private int current = 0;
private ConcreteAggregate aggregate;
public ConcreteIterator(ConcreteAggregate aggregate) {
this.aggregate = aggregate;
}
@Override
public Object first() {
return aggregate.get(0);
}
@Override
public Object next() {
current++;
if (current < aggregate.size()) {
return aggregate.get(current);
}
return null;
}
@Override
public boolean isDone() {
return (current >= aggregate.size()) ? true : false;
}
@Override
public Object currentItem() {
return aggregate.get(current);
}
}
interface Aggregate {
public Iterator CreateIterator();
}
class ConcreteAggregate implements Aggregate {
private List<Object> items = new ArrayList<Object>();
@Override
public Iterator CreateIterator() {
return new ConcreteIterator(this);
}
public int size() {
return items.size();
}
public Object get(int index) {
return items.get(index);
}
public void set(int index, Object element) {
items.set(index, element);
}
public void add(Object element) {
items.add(element);
}
}
public class IteratorPattern {
public static void main(String[] args) {
ConcreteAggregate aggregate = new ConcreteAggregate();
aggregate.add("张三");
aggregate.add("李四");
aggregate.add("王五");
aggregate.add("赵六");
Iterator iter = new ConcreteIterator(aggregate);
Object item = iter.first();
System.out.println("第一个人是:" + item);
System.out.println("所有人的名单是:");
while (!iter.isDone()) {
System.out.println(iter.currentItem());
iter.next();
}
}
}