1 概述
迭代器模式(iterator Pattern)是最常見的設計模式之一,一般使用過Java
集合的人,都接觸過這種模式。
2 迭代器模式
集合(Collection)是編程中常用的一種類型,它們是存儲元素的容器。集合有多種類型,如列表(List),集合(Set),棧(Stack),樹(Tree)等等,對於使用者來說,需要有一種統一的方式來遍歷集合中的元素。除此之外,使用者有時還需要不同的元素遍歷方式,如樹的深度優先和廣度優先遍歷。如果一味地往集合中添加遍歷方法,會使集合越來越複雜。迭代器模式對此提供瞭解決方案:提供獨立的迭代器對象來提供遍歷元素的功能。
迭代器隱藏了集合底層的細節,對外提供了一套統一的元素訪問方法。如果需要採用新的算法遍歷元素,只需要創建一個新的迭代器對象,而無需修改集合對象。
3 案例
JDK
中的Collection
很好的應用了迭代器模式。JDK
中的Iterator
接口:
public interface Iterator<E> {
boolean hasNext();
E next();
default void remove() {
throw new UnsupportedOperationException("remove");
}
* @param action The action to be performed for each element
* @throws NullPointerException if the specified action is null
* @since 1.8
*/
default void forEachRemaining(Consumer<? super E> action) {
Objects.requireNonNull(action);
while (hasNext())
action.accept(next());
}
}
主要就是兩個方法:hasNext()
和next()
。前者用來判斷集合中是否還有剩餘元素,後者用來獲取下一個元素。
一般的使用模式是:
Iterator iterator = colelction.iterator();
while(iterator.hasNext()) {
Object element = iterator.next();
// do something with the element
}
那集合是如何集成Iterator
接口的呢?以ArrayList
爲例:
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable {
// 返回一個迭代器對象,用來遍歷List中的元素
public Iterator<E> iterator() {
return new Itr();
}
private class Itr implements Iterator<E> {
// 元素遍歷的遊標
int cursor; // index of next element to return
int lastRet = -1; // index of last element returned; -1 if no such
int expectedModCount = modCount;
Itr() {}
// 如果遊標不等於List長度,說明還有元素未遍歷
public boolean hasNext() {
return cursor != size;
}
public E next() {
checkForComodification();
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
// 遊標加1,即取到下一個元素
cursor = i + 1;
return (E) elementData[lastRet = i];
}
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
@Override
@SuppressWarnings("unchecked")
public void forEachRemaining(Consumer<? super E> consumer) {
Objects.requireNonNull(consumer);
final int size = ArrayList.this.size;
int i = cursor;
if (i >= size) {
return;
}
final Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length) {
throw new ConcurrentModificationException();
}
while (i != size && modCount == expectedModCount) {
consumer.accept((E) elementData[i++]);
}
// update once at end of iteration to reduce heap write traffic
cursor = i;
lastRet = i - 1;
checkForComodification();
}
// fail-fast機制
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
}
很簡單的一個實現:每次調用next()
方法,獲取當前元素,並把遊標加1。如果cursor
小於列表長度,則說明還沒到底;如果cursor
等於列表長度,說明元素已經全部遍歷完。
可以很容易推測,對於LinkedList
的迭代器,是通過鏈表的方式,逐個訪問元素。
再看TreeSet
中的迭代器例子:
public class TreeSet<E> extends AbstractSet<E> implements NavigableSet<E>, Cloneable, java.io.Serializable {
private transient NavigableMap<E,Object> m;
/**
* Returns an iterator over the elements in this set in ascending order.
*
* @return an iterator over the elements in this set in ascending order
*/
public Iterator<E> iterator() {
return m.navigableKeySet().iterator();
}
/**
* Returns an iterator over the elements in this set in descending order.
*
* @return an iterator over the elements in this set in descending order
* @since 1.6
*/
public Iterator<E> descendingIterator() {
return m.descendingKeySet().iterator();
}
}
對於TreeSet
,默認的迭代器方法iterator()
是升序的。而調用descendingIterator()
方法便可以得到降序的迭代器。如果需要新的元素遍歷實現,則只需要新增一個對應的迭代器即可,無需改動TreeSet
原先的存儲邏輯。
4 總結
迭代器模式提供了集合中元素的統一訪問方式,解藕了元素遍歷與元素存儲,是非常重要的一種設計模式。