概念
抽象循环变量的功能
必要性
将被遍历对象的实现和其遍历解耦
如果不这么做,那么很可能修改了类的实现就要继续修改遍历的代码
场景
任意有可能更改实现的数据集类中通用的遍历方案
//待遍历的数据集类要实现这个接口,具备迭代器方法,返回一个迭代器
public interface Aggregate {
public abstract Iterator iterator();
}
//待遍历的数据集类,是一个书架,书架上有很多书
//可以换成额任意其他的数据集,比如衣橱,购物车商品……
public class bookShelf implements Aggregate{
private int Max;
private book[] books;
private int last;
public bookShelf(int max){
books = new book[max];
this.last = 0;
}
@Override
public Iterator iterator() {
return new bookShelfIterator(this);
}
public void append(String name){
books[last] = new book(name);
last++;
}
public book getBookByIndex(int index){
return books[index];
}
public int getLength(){
return last;
}
}
//迭代器接口,用来规定实现类要实现的功能
public interface Iterator {
public abstract boolean hasNext();
public abstract Object next();
}
//迭代器实现类,实现了迭代器接口,要拿到待迭代的数据集,初始化迭代器的下标
public class bookShelfIterator implements Iterator{
private bookShelf bs;
private int index;
public bookShelfIterator(bookShelf bs){
this.bs = bs;
index = 0;
}
@Override
public boolean hasNext() {
if(index < bs.getLength()){
return true;
} else {
return false;
}
}
@Override
public Object next() {
book bk = bs.getBookByIndex(index);
index++;
return bk;
}
}
//数据集类中的数据元素类,这里就是书,构造器拿到书名,getName让书架查看书
public class book {
private String name;
public book(String name){
this.name = name;
}
public String getName(){
return name;
}
}
测试类
//加了两本书到书架中,然后通过书架的迭代器来进行遍历书架,而不是一般的通过for int i = 0 这种
public class Main {
public static void main(String[] args){
bookShelf bs = new bookShelf(2);
bs.append("毛泽东选集");
bs.append("人生的智慧");
Iterator it = new bookShelfIterator(bs);
while(it.hasNext()){
book bk = (book)it.next();
System.out.println(bk.getName());
}
}
}