迭代器模式用於迭代集合對象,他是一個很經常使用的模式,你能夠在以前使用過他,可能你見過像hasNext()和next(),他多是迭代器模式,好比,你可能迭代訪問數據庫記錄。java
interface IIterator{ public boolean hasNext(); public Object next(); } interface IContainer{ public IIterator createIterator(); } class RecordCollection implements IContainer{ private String recordArray[] = {"first","second","third","fourth","fifth"}; public IIterator createIterator(){ RecordIterator iterator = new RecordIterator(); return iterator; } private class RecordIterator implements IIterator{ private int index; public boolean hasNext(){ if (index < recordArray.length) return true; else return false; } public Object next(){ if (this.hasNext()) return recordArray[index++]; else return null; } } } public class TestIterator { public static void main(String[] args) { RecordCollection recordCollection = new RecordCollection(); IIterator iter = recordCollection.createIterator(); while(iter.hasNext()){ System.out.println(iter.next()); } } }
在 java.util包中,迭代器的接口定義以下: 這些類能夠建立迭代器TreeSet#iterator(), HashSet#iterator(),等數據庫
public interface Iterator { boolean hasNext(); E next(); void remove(); }