迭代器模式定义:
迭代器模式(Iterator),提供一种方法顺序访问一个聚合对象中的各种元素,而又不暴露该对象的内部表示。
类图:
Talk is cheap, show me the code:
interface Iterator<T> {
public boolean hasNext();
public T next();
}
class ConcreteIterator<T> implements Iterator {
T[] array = null;
int size;
int cursor;
public ConcreteIterator(T[] array,int size) {
super();
this.array = array;
this.size = size;
this.cursor = 0;
}
@Override
public boolean hasNext() {
if (cursor >= size) {
return false;
} else {
return true;
}
}
@Override
public Object next() {
T object = array[cursor];
cursor++;
return object;
}
}
interface Aggregate<T> {
public void add(T obj);
public T get(int index);
public Iterator iterator();
public int getSize();
}
class ConcreteAggregate<T> implements Aggregate{
private Object[] array;
private int size=0;
private int index=0;
private int max;
public ConcreteAggregate(int size){
this.index=0;
this.size=0;
this.array=new Object[size];
this.max = size;
}
@Override
public void add(Object obj){
// 为了代码简单,这里直接抛出异常。
if(index >= max){
throw new RuntimeException();
}
array[index++]= obj;
size++;
}
@Override
public Iterator iterator() {
return new ConcreteIterator(array,size);
}
@Override
public T get(int index) {
return (T)array[index];
}
@Override
public int getSize() {
return size;
}
}
class IteratorTest {
/**
* @param args
*/
public static void main(String[] args) {
Aggregate<String> list = new ConcreteAggregate<String>(100);
list.add("a");
list.add("b");
list.add("c");
list.add("d");
Iterator it=list.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}
}
打印结果:
a
b
c
d
欢迎关注我的微信公众号: