上周六就開始寫這篇博客,之后一直耽誤了。到前天才開始寫。今天醒的早,就把這部分整理一下。
本文內容參考易學設計模式和馬士兵的迭代器模式的視頻。
了解迭代器模式一個作用就是讓你在使用 迭代器遍歷集合類的時候 認為更自然。'
一 、迭代器模式簡單介紹
【定義】 跌倒器模式提供一種順序訪問一個聚合對象中各個元素,而又不暴露該對象的內部表示的方法。
【原理】 主要4部分組成:迭代器角色、詳細迭代器角色、容器角色和詳細容器角色。
【使用時機】當訪問一個聚合對象的內容而無需暴露它的內部表示,或者須要支持對集合對象的多種遍歷。或者為
遍歷不同的聚合結構提供一個統一的接口時,就能夠考慮是用迭代器模式。
二 、實現ArrayList和linkedList的迭代器
這里僅僅是簡單實現,詳細的能夠看看源代碼。記得csdn中有一個 蘭亭風雨 的博客寫有集合類源代碼解析的文章。
上代碼:
Iterator.java
package com.chan;
public interface Iterator {
Object next();
boolean hasNext();
}
Collection.java
package com.chan;
public interface Collection {
void add(Object obj);
int size();
Iterator iterator();
}
Node,java
package com.chan;
public class Node {
private Object data;
private Node next;
public Node(Object data, Node next) {
super();
this.data = data;
this.next = next;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}
ArrayList.java
package com.chan;
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;
}
}
}
LinkedList.java
package com.chan;
public class LinkedList implements Collection {
Node head = null;
Node tail = null;
int size = 0;
public void add(Object o) {
Node n = new Node(o, null);
if(head == null) {
head = n;
tail = n;
}
tail.setNext(n);
tail = n;
size ++;
}
public int size() {
return size;
}
@Override
public Iterator iterator() {
return new LinkedListIterator();
}
private class LinkedListIterator implements Iterator{
private Node currentNode = head;
private int nextIndex = 0;//參考源代碼中的寫法
@Override
public Object next() {
Object data = currentNode.getData();
currentNode = currentNode.getNext();
nextIndex ++;
return data;
}
@Override
public boolean hasNext() {
return nextIndex != size;
}
}
}
Test>java
package com.chan;
public class Test {
public static void main(String[] args) {
//Collection c = new ArrayList();
Collection c = new LinkedList();
for(int i=0; i<15; i++){
c.add("test-"+i);
}
System.out.println(c.size());
Iterator it = c.iterator();
while(it.hasNext()) {
Object o = it.next();
System.out.print(o + " ");
}
}
//15
//test-0 test-1 test-2 test-3 test-4 test-5 test-6 test-7 test-8 test-9 test-10 test-11 test-12 test-13 test-14
}
以上代碼測試通過。
