iterator模式(遍历模式、迭代器模式)
最开始,我们使用的遍历通常是获取数组长度来循环输出
for(int i = 0; i < arr.length; i++){
System.out.print(arr[i])
}
以上代码,我们将获取循环变量i给抽象出来,使得我们更加快速的循环遍历数组
示例程序
// AggreGate 接口
// 所需要遍历的集合的接口
public interface AggreGate{
public abstract Iterator iterator();
}
// Iterator 接口
// 用于遍历集合中元素的接口
public interface Iterator{
public abstract boolean hasNext();
public abstract Object next();
}
// Book 类
// 我们所需要遍历的对象
public class Book{
private String name;
public Book(String name){
this.name = name;
}
public String getName(){
return name;
}
}
// BookShelf 类
// 实现Aggregate接口,处理集合类
public class BookShelf implements Aggregate{
private Book[] books;
private int last=0;
public BookShelf(int maxsize){
this.books = new Book[maxsize];
}
public getBookAt(int index){
return books[index];
}
public void appendBook(Book book){
this.books[last] = book;
last;
}
public int getLength(){
return last;
}
public Iterator iterator(){
return new BookShelfIterator(this);
}
}
// BookShelfIterator 类
// 用于遍历的类,实现Iterator接口
public class BookShelfIterator implements Iterator{
private BookShelf bookShelf;
private int index;
public BookShelfIterator(BookShelf bookShelf){
this.bookShelf = bookShelf;
this.index = 0;
}
public boolean hasNext(){
if(index < bookShelf.getLength()){
return true;
}else{
return false;
}
}
public Object next(){
Book book = bookShelf.getBookAt(index);
index++;
return book;
}
// 主函数
public class Main{
public static void main(String[] args){
// 设置集合
BookShelf bookShelf = new BookShelf(4);
// 添加书籍
bookShelf.appendBook(new Book("名称"));
bookShelf.appendBook(new Book("名称"));
bookShelf.appendBook(new Book("名称"));
bookShelf.appendBook(new Book("名称"));
// 获取用于遍历的Iterator
Iterator it = bookShelf.iterator();
while(it.hasNext()){
Book book = (Book)it.next();
// 处理对象代码
.........
}
}
}
}
出现的角色
Iterator(迭代器) -->Iterator接口
ConcreteIterator(具体的迭代器)-->BookShelfIterator实现类
Aggregate(集合) --> Aggregate接口
ConcreteAggregate(具体的集合)--> BookShelf实现类
要点
不管如何实现如何变化,都可以使用Iterator,将遍历与实现分离开
不需要对大部分代码进行修改,只需要对Iterator方法修改,代码就可以正常工作。
相关的设计模式
Visitor模式 Composite模式 Factory Method模式