迭代器模式
分析
定义:迭代器模式用于顺序访问集合对象的元素,不需要知道集合对象的底层表示。
迭代器包含以下角色:
- Aggregate:抽象集合,定义创建迭代器的接口
- terator:抽象迭代器,定义访问和遍历元素的接口
- ConcreteIterator:实现访问和遍历元素的接口
- ConcreteAggregate:具体集合,实现迭代器接口
在迭代器模式中,增加新的聚合类和迭代器类都很方便,无须修改原有代码
在同一个聚合上可以有多个遍历,简化了聚合类。
案例:迭代器的实现
//Aggregate
public interface Iterable<T> {
public abstract Iterator<T> iterator();
}
//iterator
public interface Iterator<T> {
public abstract Object next();
public abstract boolean hasNext();
}
//ConcreteAggregate
public class IntegerList implements Iterable{
private List<Integer> list = new ArrayList<>();
public void add(Integer e){
list.add(e);
}
protected int size(){
return list.size();
}
protected Integer get(int index){
return list.get(index);
}
@Override
public Iterator iterator() {
return new IteratorA(this);
}
}
//ConcreteIterator
public class IteratorA implements Iterator{
private IntegerList e;
private int index = 0;
public IteratorA(IntegerList integerList) {
e = integerList;
}
@Override
public Object next() {
if(hasNext()){
return e.get(index++);
}else{
throw new RuntimeException("");
}
}
@Override
public boolean hasNext() {
return index < e.size()? true:false;
}
}
//Client
public class Test {
public static void main(String[] args){
IntegerList list = new IntegerList();
list.add(20);
list.add(30);
list.add(40);
list.add(50);
Iterator<Integer> iterator = list.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
}
}