迭代器模式
忽然看到迭代器模式,在集合中能经常遇到
1.迭代器模式(Iterator Pattern)
使用者不需要知道对象内部结构,便可遍历对象内部的元素
迭代器模式的组成:
- Iterator:迭代器接口
- Container:迭代器容器接口
- ContainerConcrete:容器实现类
2.流程
2.1 Iterator
public interface Iterator<E> {
boolean hasNext();
E next();
}
2.2 Container
public interface Container<E> {
Iterator<E> iterator();
}
2.3 ContainerConcrete
public class ContainerConcrete<E> implements Container {
// 存放的元素
public String[] elements = {"A", "B", "C", "D"};
@Override
public Iterator iterator() {
return new IteratorConcrete();
}
private class IteratorConcrete<E> implements Iterator {
int index;
@Override
public boolean hasNext() {
if (index < elements.length) {
return true;
}
return false;
}
@Override
public E next() {
if (this.hasNext()) {
return (E) elements[index++];
}
return null;
}
}
}
2.4 测试
public class Test {
public static void main(String[] args) {
ContainerConcrete containerConcrete = new ContainerConcrete();
Iterator iterator = containerConcrete.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}