顧名思義,迭代器模式就是順序訪問彙集中的對象,通常來講,集合中很是常見,若是對集合類比較熟悉的話,理解本模式會十分輕鬆。這句話包含兩層意思:一是須要遍歷的對象,即彙集對象,二是迭代器對象,用於對彙集對象進行遍歷訪問。咱們看下關係圖:java
這個思路和咱們經常使用的如出一轍,MyCollection中定義了集合的一些操做,MyIterator中定義了一系列迭代操做,且持有Collection實例,咱們來看看實現代碼:設計模式
兩個接口:框架
public interface Collection { public Iterator iterator(); /*取得集合元素*/ public Object get(int i); /*取得集合大小*/ public int size(); }
public interface Iterator { //前移 public Object previous(); //後移 public Object next(); public boolean hasNext(); //取得第一個元素 public Object first(); }
兩個實現:ide
public class MyCollection implements Collection { public String string[] = {"A","B","C","D","E"}; @Override public Iterator iterator() { return new MyIterator(this); } @Override public Object get(int i) { return string[i]; } @Override public int size() { return string.length; } }
public class MyIterator implements Iterator { private Collection collection; private int pos = -1; public MyIterator(Collection collection){ this.collection = collection; } @Override public Object previous() { if(pos > 0){ pos--; } return collection.get(pos); } @Override public Object next() { if(pos<collection.size()-1){ pos++; } return collection.get(pos); } @Override public boolean hasNext() { if(pos<collection.size()-1){ return true; }else{ return false; } } @Override public Object first() { pos = 0; return collection.get(pos); } }
測試類:測試
public class Test { public static void main(String[] args) { Collection collection = new MyCollection(); Iterator it = collection.iterator(); while(it.hasNext()){ System.out.println(it.next()); } } }
輸出:A B C D E優化
此處咱們貌似模擬了一個集合類的過程,感受是否是很爽?其實JDK中各個類也都是這些基本的東西,加一些設計模式,再加一些優化放到一塊兒的,只要咱們把這些東西學會了,掌握好了,咱們也能夠寫出本身的集合類,甚至框架!this