迭代器模式(Iterator), Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation. (它提供一各方法訪問一個窗口對象中各個元素,而又不需暴露該對象的內部細節。)html
通用類圖:java
角色:ide
1. Iterator抽象迭代器:負責定義訪問和遍歷元素的接口。在Java中,只迭代器爲interface,其中定義了三個方法,hasNext(), next(), remove().ui
2. ConcreteIterator具體迭代器:實現迭代器接口,完成元素的遍歷。持有容器的引用以完成遍歷。this
3. Aggregate抽象容器: 負責建立具體迭代器角色的接口,必須提供相似createIterator()這樣的方法。在Java中,通常是iterator()方法。spa
4. ConcreteAggregate具體容器。code
JDK中Iterator接口htm
/* * Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package java.util; /** * An iterator over a collection. {@code Iterator} takes the place of * {@link Enumeration} in the Java Collections Framework. Iterators * differ from enumerations in two ways: * * <ul> * <li> Iterators allow the caller to remove elements from the * underlying collection during the iteration with well-defined * semantics. * <li> Method names have been improved. * </ul> * * <p>This interface is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * * @param <E> the type of elements returned by this iterator * * @author Josh Bloch * @see Collection * @see ListIterator * @see Iterable * @since 1.2 */ public interface Iterator<E> { /** * Returns {@code true} if the iteration has more elements. * (In other words, returns {@code true} if {@link #next} would * return an element rather than throwing an exception.) * * @return {@code true} if the iteration has more elements */ boolean hasNext(); /** * Returns the next element in the iteration. * * @return the next element in the iteration * @throws NoSuchElementException if the iteration has no more elements */ E next(); /** * Removes from the underlying collection the last element returned * by this iterator (optional operation). This method can be called * only once per call to {@link #next}. The behavior of an iterator * is unspecified if the underlying collection is modified while the * iteration is in progress in any way other than by calling this * method. * * @throws UnsupportedOperationException if the {@code remove} * operation is not supported by this iterator * * @throws IllegalStateException if the {@code next} method has not * yet been called, or the {@code remove} method has already * been called after the last call to the {@code next} * method */ void remove(); }