迭代器模式(Iterator)提供一種方法順序訪問一個聚合對象中的各類元素,而又不暴露對象的內部表示。java
類型:形爲型模式 git
順口溜:中訪策備迭 觀模命狀職解github
package com.amosli.dp.behavior.iterator; public abstract class Aggregate { public abstract Iterator ConcreteIterator(); } package com.amosli.dp.behavior.iterator; public abstract class Iterator { public abstract Object first(); public abstract Object last(); public abstract Object next(); public abstract Boolean isDone(); public abstract Object currentItem(); } package com.amosli.dp.behavior.iterator; import java.util.ArrayList; import java.util.List; public class ConcreteAggregate extends Aggregate { private List<Object> items = new ArrayList<Object>(); @Override public Iterator ConcreteIterator() { return new ConcreteIterator(this); } public Object get(int index) { return items.get(index); } public int size() { return items.size(); } public void add(Object obj) { items.add(obj); } } package com.amosli.dp.behavior.iterator; public class ConcreteIterator extends Iterator { private ConcreteAggregate concreteAggregate; public ConcreteIterator(ConcreteAggregate concreteAggregate) { this.concreteAggregate = concreteAggregate; } private int count=0; @Override public Object first() { return concreteAggregate.get(0); } @Override public Object last() { return concreteAggregate.get(concreteAggregate.size() - 1); } @Override public Object next() { return concreteAggregate.get(count++); } @Override public Object currentItem() { return concreteAggregate.get(count); } @Override public Boolean isDone() { return count >= concreteAggregate.size(); } } package com.amosli.dp.behavior.iterator; public class Client { public static void main(String[] args) { ConcreteAggregate aggregate = new ConcreteAggregate(); for (int i = 0; i < 10; i++) { aggregate.add("i" + i); } ConcreteIterator iterator = new ConcreteIterator(aggregate); System.out.println(aggregate.size()); System.out.println("first:" + iterator.first()); System.out.println("last:" + iterator.last()); System.out.println("current:" + iterator.last()); while (!iterator.isDone()) { System.out.println(iterator.next()); } System.out.println("over"); } }
當你須要訪問一個聚合對象,並且無論這些對象是什麼都須要遍歷的時候,就應該考慮使用迭代器模式。算法
另外,當須要對彙集有多種方式遍歷時,能夠考慮去使用迭代器模式。數組
簡化了遍歷方式,對於對象集合的遍歷,仍是比較麻煩的,對於數組或者有序列表,咱們尚能夠經過遊標來取得,但用戶須要在對集合瞭解很清楚的前提下,自行遍歷對象,可是對於hash表來講,用戶遍歷起來就比較麻煩了。而引入了迭代器方法後,用戶用起來就簡單的多了。ide
能夠提供多種遍歷方式,好比說對有序列表,咱們能夠根據須要提供正序遍歷,倒序遍歷兩種迭代器,用戶用起來只須要獲得咱們實現好的迭代器,就能夠方便的對集合進行遍歷了。this
封裝性良好,用戶只須要獲得迭代器就能夠遍歷,而對於遍歷算法則不用去關心。spa
對於比較簡單的遍歷(像數組或者有序列表),使用迭代器方式遍歷較爲繁瑣,你們可能都有感受,像ArrayList,咱們寧肯願意使用for循環和get方法來遍歷集合。code
本系列文章源碼地址,https://github.com/amosli/dp 歡迎Fork & Star !!orm