定义
Iterator 模式用于在数据集合中按照顺序遍历集合
主要角色
Iterator(迭代器)
这是一个接口,定义了两个方法 next 和 hasNext,分别用来获取下一个元素或者判断是否有下一个元素
ConcreteIterator(具体的迭代器)
负责实现 Iterator 角色所定义的接口
Aggregate(集合)
负责定义创建 Iterator 角色的接口
ConcreteAggregate(具体的集合)
负责实现 Aggregate 角色中所定义的接口
实例代码
- 迭代器
public interface Iterator {
boolean hasNext();
Object next();
}
- 集合
/**
* 用来获取迭代器
*/
public interface Aggregate {
Iterator iterator();
}
- 具体的迭代器
public class BookShelfIterator implements Iterator{
private BookShelf bookShelf;
private int index;
public BookShelfIterator(BookShelf bookShelf) {
this.bookShelf = bookShelf;
this.index = 0;
}
@Override
public boolean hasNext() {
if (index < bookShelf.getLength()) {
return true;
}
return false;
}
@Override
public Object next() {
return this.bookShelf.getBook(index++);
}
}
- 具体的集合
public class BookShelf implements Aggregate{
private Book[] books;
private int last;
public BookShelf(int maxSize) {
if (maxSize <= 0) {
throw new IllegalArgumentException("参数不合适");
}
this.books = new Book[maxSize];
this.last = 0;
}
public void appendBook(Book book) {
if (last >= books.length) {
throw new IndexOutOfBoundsException("数组越界");
}
this.books[last] = book;
last++;
}
public Book getBook(int index) {
if (index >= books.length || index < 0) {
throw new IndexOutOfBoundsException("数组越界");
}
return books[index];
}
public int getLength() {
return this.last;
}
@Override
public Iterator iterator() {
return new BookShelfIterator(this);
}
}
- 实体类
public class Book {
private String name;
public Book(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
- 每一个集合都对应的一个集合的迭代器,而这些集合和集合对应的迭代器都有固定的接口,这些接口定义了固定的方法;
- 集合对应的集合迭代器需要获取到该集合的类,才能开始遍历,即传入 this
总结
- 引入 Iterator后可以将遍历和实现分离开来,迭代器的循环遍历不依赖于具体集合的实现;
- next 方法的作用:返回当前元素并且指向下一个元素;
- hasNext方法的作用:确认接下来是否可以调用 next 方法;
- 迭代器的遍历不仅可以从前往后遍历,还可以更改其方向。