DIV CSS 佈局教程網

Java 設計模式之迭代器模式:手寫一個簡化版 ArrayList
編輯:關於JavaScript     

迭代器模式的作用,是為不同的容器提供統一的遍歷方式——使用者不必關心底層是數組、鏈表還是哈希結構,只需反覆調用 hasNext() 與 next()。本文以 Java 集合為原型,從零模擬一遍它的原理。

一、定義容器接口 Collection

package com.njupt.zhb.learn.iterator;
public interface Collection {
  void add(Object o);
  int size();
  Iterator iterator();
}

注意第三個方法:容器只負責「生產」迭代器,不負責遍歷細節。

二、定義迭代器接口 Iterator

package com.njupt.zhb.learn.iterator;
public interface Iterator {
  Object next();
  boolean hasNext();
}

三、實現 ArrayList

用數組存數據,容量不夠時自動翻倍擴容;迭代器以內部類形式實現,各自持有獨立的游標:

package com.njupt.zhb.learn.iterator;
import com.njupt.zhb.learn.iterator.Collection;
public class ArrayList implements Collection {
  Object[] objects = new Object[10];
  int index = 0;
  public void add(Object o) {
    if(index == objects.length) {
      Object[] newObjects = new Object[objects.length * 2];
      System.arraycopy(objects, 0, newObjects, 0, objects.length);
      objects = newObjects;
    }
    objects[index] = o;
    index ++;
  }

  public int size() {
    return index;
  }

  public Iterator iterator() {
    return new ArrayListIterator();
  }

  private class ArrayListIterator implements Iterator {
    private int currentIndex = 0;
    @Override
    public boolean hasNext() {
      if(currentIndex >= index) return false;
      else return true;
    }
    @Override
    public Object next() {
      Object o = objects[currentIndex];
      currentIndex ++;
      return o;
    }
  }
}

兩個細節值得留意:游標 currentIndex 是迭代器自己的成員,所以同一容器可以同時有多個迭代器互不干擾;內部類能直接訪問外部類的 index 與 objects,無需暴露私有字段。

四、測試程序

package com.njupt.zhb.learn.iterator;
import com.njupt.zhb.learn.iterator.ArrayList;
public class TestMain {
  public static void main(String[] args) {
    Collection c = new ArrayList();
    for(int i=0; i<15; i++) {
      c.add("string "+i);
    }
    System.out.println(c.size());
    Iterator it = c.iterator();
    while(it.hasNext()) {
      Object o = it.next();
      System.out.println(o.toString() + " ");
    }
  }
}

五、運行結果

15
string 0
string 1
string 2
string 3
string 4
string 5
string 6
string 7
string 8
string 9
string 10
string 11
string 12
string 13
string 14

六、模式要點

  • 職責分離。容器管存儲,迭代器管遍歷,兩者通過接口解耦。JDK 的 ArrayList、LinkedList 正是這一思路的工業級實現。
  • 面向接口編程。TestMain 中聲明的是 Collection 而非 ArrayList,替換實現時調用方無需改動——這就是多態的價值。
  • JDK 的增強版。實際開發中請直接用 for-each 或 Iterator,並注意 Collection.removeIf、ListIterator 等能力;此外 fail-fast 機制(modCount 檢查)是我這個簡化版沒有的,遍歷中修改集合會拋 ConcurrentModificationException。
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved