概念:提供一种方法顺序访问一个聚合对象中各个元素,而又不暴露该对象的内部表示
应用:java的foreach
java代码:
public class IteratorTest {
public static void main(String[] args) {
Aggregate aggregate = new ConcreteAggregate();
aggregate.Add(new Object());
aggregate.Add(new Object());
Iterator iterator = aggregate.CreateIterator();
while(!iterator.IsDone()){
System.out.println(iterator.CurrentItem());
iterator.Next();
}
}
}
//迭代器抽象类
public abstract class Iterator {
public abstract Object First();
public abstract Object Next();
public abstract boolean IsDone();
public abstract Object CurrentItem();
}
//迭代器类
public class ConcreteIterator extends Iterator {
Aggregate aggregate;
int current = 0;
public ConcreteIterator(Aggregate aggregate) {
this.aggregate = aggregate;
}
@Override
public Object First() {
return aggregate.getObject(0);
}
@Override
public Object Next() {
Object temp = aggregate.getObject(current);
current++;
return temp;
}
@Override
public boolean IsDone() {
if (aggregate.Count() == current) {
return true;
}
return false;
}
@Override
public Object CurrentItem() {
return aggregate.getObject(current);
}
}
//遍历对象抽象类
public abstract class Aggregate {
public abstract Iterator CreateIterator();
public abstract Object getObject(int index);
public abstract int Count();
public abstract void Add(Object object);
}
//遍历对象实现类
public class ConcreteAggregate extends Aggregate {
List<Object> list = new ArrayList<>();
@Override
public Iterator CreateIterator() {
return new ConcreteIterator(this);
}
public Object getObject(int index){
return list.get(index);
}
@Override
public int Count() {
return list.size();
}
@Override
public void Add(Object object) {
list.add(object);
}
}