1、迭代器模式
提供一种方法顺序访问一个聚合对象中各个元素,而又不需要暴露该对象的内部表示。
一是需要遍历的对象,即聚集对象;二是迭代器对象,用于对聚集对象进行遍历访问;
实例一
// 定义集合接口
public interface Collection {
public Iterator iterator();
public int size();
public Object get(int index);
}
// 定义迭代器接口
public interface Iterator {
// 前移
public Object pre();
// 后移
public Object next();
public boolean hasNext();
public Object first();
}
public class MyCollection implements Collection {
private String[] context = { "1", "2", "3", "4" };
@Override
public Iterator iterator() {
return new MyIterator(this);
}
@Override
public int size() {
return this.context.length;
}
@Override
public Object get(final int index) {
if (index < this.context.length) {
return this.context[index];
}
return null;
}
}
public class MyIterator implements Iterator {
private Collection cols;
// 初始化集合下标位置为0
private int position = -1;
public MyIterator(final Collection col) {
this.cols = col;
}
@Override
public Object pre() {
if (this.position > 0) {
this.position--;
return this.cols.get(this.position);
}
return null;
}
@Override
public Object next() {
if (this.position < this.cols.size()) {
this.position++;
return this.cols.get(this.position);
}
return null;
}
@Override
public boolean hasNext() {
if (this.position < (this.cols.size() - 1)) {
return true;
}
return false;
}
@Override
public Object first() {
return this.cols.get(0);
}
}
模拟调用:
public static void main(final String[] args) {
final Collection cols = new MyCollection();
final Iterator ite = cols.iterator();
while (ite.hasNext()) {
final Object obj = ite.next();
System.out.println("~~~~ : " + obj);
}
}