轉載請註明出處:http://blog.csdn.net/lhy_ycu/article/details/39807741
迭代器模式(Iterator):提供了一種方法順序訪問一個聚合對象中的各個元素,而又不暴露其內部的表示。
一、uml建模:
二、代碼實現
/**
* 示例:迭代器模式
*
*/
interface Iterator {
/** 前移 */
public Object previous();
/** 後移 */
public Object next();
/** 判斷是否有下一個元素 */
public boolean hasNext();
}
interface Collection {
public Iterator iterator();
/** 取得集合中的某個元素 */
public Object get(int i);
/** 取得集合大小 */
public int size();
}
/**
* 集合
*/
class MyCollection implements Collection {
private String[] strArray = { "aa", "bb", "cc", "dd" };
@Override
public Iterator iterator() {
return new MyIterator(this);
}
@Override
public Object get(int i) {
return strArray[i];
}
@Override
public int size() {
return strArray.length;
}
}
/**
* 迭代器
*/
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;
}
return false;
}
}
/**
* 客戶端測試類
*
* @author Leo
*/
public class Test {
public static void main(String[] args) {
/**
* 實例化容器
*/
Collection collection = new MyCollection();
/**
* 創建迭代器
*/
Iterator iterator = collection.iterator();
/**
* 遍歷集合中的元素
*/
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}
三、應用場景
遍歷、訪問集合中的某個元素等
四、總結
迭代器模式就是順序訪問集合中的對象,這句話包含兩層意思:一是需要遍歷的對象,即集合對象,二是迭代器對象,用於對集合對象進行遍歷訪問。