迭代器模式(java版)

迭代器模式的组成部分

Aggregate(抽象聚合类)

它用于存储和管理元素对象,声明一个createiterator()方法用于创建一个迭代器对象,充当抽象迭代器工厂角色。

ConcreteAggregate(具体聚合类)

它用于抽象聚合类的子类,实现了在抽象集合类中的声明的createIterator()方法,该方法返回一个与该具体聚合类对应的具体迭代器ConcreteIterator实例。

Iterator

它定义了访问和遍历元素的接口,声明了用户遍历数据元素的方法。

first()://用于获取第一个元素

next();//用于访问下一个元素

hasnext();//用于判断是否还有下一个元素

currentitem();//用于获取当前元素

ConcreteIterator

它实现了抽象迭代器接口,完成了对聚合对象的遍历,同时在具体迭代器中通过游标访问来标记在聚合对象中所处的当前位置,在具体实现时,游标通常是一个表示位置的非负整数。

代码如下:

package com.china.wanson;

public interface Iterator {
public boolean hasNext();
public Object next();

}


package com.china.wanson;

public interface List {
public void add(Object object);
public Object get(int index);
public Iterator interator();
public int getSize();

}

package com.china.wanson;

public class ConcreteAggregate implements List{

private Object[] list;
private int size=0;
private int index=0;


public void add(Object object) {
list[index++]=object;
size++;
}

public Object get(int index) {

return list[index];
}

public Iterator interator() {

return new ConcreteIterator(this);
}

public int getSize() {
return size;
}
}



package com.china.wanson;



public class ConcreteIterator implements Iterator {
private List list=null;
private int index;

public ConcreteIterator(List list){
super();
this.list=list;
}

public boolean hasNext() {
if(index>=list.getSize()){
return false;
}else{
return true;
}
}

public Object next() {
Object object=list.get(index++);
return object;
}
}

猜你喜欢

转载自www.cnblogs.com/wq-9/p/10120668.html