1.定义#
提供一种方法访问一个容器对象中各个元素,而又不需要暴露该对象的内部细节。大部分语言中已经在常用数据结构类型中实现,不需要自己动手实现。主要用于遍历一个容器对象。实现中迭代器类主要用一个游标在容器元素间前后移动。
2.类图#
3.实现#
3.1抽象迭代器##
public interface Iterator{
public Object next();
public boolean hasNext();
public boolean remove();
}
3.2具体迭代器##
public class ConcreteIterator implements Iterator {
private ArrayList<T> arrayList = new ArrayList<T>();
public int cursor = 0;
public ConcreteIterator(ArryaList<T> _arrayList){
this.arrayList = _arrayList;
}
public boolean hasNext(){
if(this.cursor == this.arrayList.size())
{
return false;
}else{
return true;
}
}
public Object next(){
Object result = null;
if(this.hasNext){
result = this.arrayList.get(this.cursor++);
}else{
result = null;
}
return result;
}
public boolean remove(){
this.arryaList.remove(this.cursor--);
}
}
3.3抽象容器类##
public interface Aggregate{
public void add(Object object);
public void remove(Object object);
public Iterator iterator();
}
3.4具体容器类##
public class ConcreteAggregate implements Aggregate{
private ArrayList arrayList = new ArrayList();
public void add(Object object){
this.arrayList.add(object);
}
public Iterator iterator(){
return new ConcreteIterator(this.arrayList);
}
public void remove(){}
}