概述
給定一個語言
適用性
參與者
迭代器定義訪問和遍歷元素的接口
具體迭代器實現迭代器接口
對該聚合遍歷時跟蹤當前位置
聚合定義創建相應迭代器對象的接口
具體聚合實現創建相應迭代器的接口
類圖
示例代碼:
package com
import java
import java
/**
* 迭代器模式 實現示例
* @author sean
*/
interface IIterator<T> {
T next();
void first();
void last();
boolean hasNext();
}
class IIteratorImpl<T> implements IIterator<T> {
private IList<T> list;
private int index;
public IIteratorImpl (IList<T> list) {
index =
this
}
@Override
public T next() {
T t = list
index++;
return t;
}
@Override
public void first() {
index =
}
@Override
public void last() {
index = list
}
@Override
public boolean hasNext() {
return index < list
}
}
interface IList<T> {
IIterator<T> iterator();
T get(int index);
int size();
void add(T obj);
}
class IListImpl<T> implements IList<T> {
private List<T> list;
private int index;
public IListImpl() {
list = new ArrayList<T>();
index =
}
@Override
public IIterator<T> iterator() {
return new IIteratorImpl<T> (this);
}
@Override
public T get(int index) {
return list
}
@Override
public int size() {
return list
}
@Override
public void add(T obj) {
list
}
}
public class IteratorTest {
public static void main(String[] args) {
//
IList<String> list = new IListImpl<String>();
list
list
list
//
System
IIterator<String> iter = erator();
while (iter
System
}
//
System
for (int i=
System
}
}
}
結果:
a
b
c
a
b
c
From:http://tw.wingwit.com/Article/program/Java/gj/201311/27448.html