迭代器模式用於順序訪問集合對象的元素,而無需知道集合的底層表示,屏蔽了細節用一種更便攜的方式訪問集合對象。html
定義一個獲取迭代對象的接口ide
public interface Container { public Iterator getIterator(); }
定義迭代對象方法spa
public interface Iterator { public boolean hasNext(); public Object next(); }
建立一個集合類時,須要在該集合類中添加一個內部類實現Iterator接口,用於判斷是否有元素及獲取元素。code
集合類須要實現Container接口,提供一個獲取實現了Iterator的內部類對象的方法,用於後續遍歷。htm
//模擬集合類 public class NameRepository implements Container{ private String[] names = {"hcf","zrx","gcmh"}; //獲取實現了Iterator接口的內部類 @Override public Iterator getIterator() { // TODO Auto-generated method stub return new NameRepositoryIterator(); } //集合內部實現Iterator接口的內部類。 private class NameRepositoryIterator implements Iterator{ private int index = (names != null && names.length > 0) ? 0 : -1; @Override public boolean hasNext() { // TODO Auto-generated method stub if(index < names.length) { return true; }else { return false; } } @Override public Object next() { // TODO Auto-generated method stub return names[index++]; } } }
Main對象
public class Main { public static void main(String[] args) { NameRepository nameRepository = new NameRepository(); Iterator ite = nameRepository.getIterator(); while(ite.hasNext()) { System.out.println(ite.next()); } } }
運行結果:
hcf
zrx
gcmh
參考資料:blog
https://www.runoob.com/design-pattern/iterator-pattern.html接口