一句话概述Iterator模式
使用迭代器一个个的遍历出集合中的元素
Iterator模式中四个主要的类和接口
Iterator(interface)
迭代器的接口。
首先,我们要知道迭代器的作用----遍历集合的元素。所以其主要的两个方法为hasNext、next。
hasNext用于判断是否还有下一个元素、next用于取出当前元素,并且指向下一个元素(注意,这里的next是获取当前)
ConcreteIterator(class)
该类就是要实现Iterator,是一个确切的迭代器,实现hasNext、next方法
其内应该有个具体的集合,就是我们需要迭代的对象
该类还应该有个index变量,获取当前的索引,用于判断是否hasNext
Aggregate(interface)
集合的接口,实现该接口的表明就是一个确切的集合
该接口提供方法去创建一个Iterator
ConcreteAggregate(class)
实现Aggregate,一个确切的集合
其实现的createIterato方法创建对应的Iterator
UML图
具体案例
使用书上的案例,从BookShelf中迭代出所有书籍
Aggregate
package com.cutezha.Iterator;
public interface Aggregate {
public abstract Iterator createIterator();
}
Iterator
package com.cutezha.Iterator;
public interface Iterator {
public abstract boolean hasNext();
public abstract Object next();
}
Book
package com.cutezha.Iterator;
public class Book {
private String name;
public Book(String name){
this.name = name;
}
public String getName(){
return name;
}
}
BookShelf
书上的原内容是使用的数组,我这里使用ArrayList其实本来就是个集合了,只不过我多写了个createIterator方法,创建相应的迭代器
package com.cutezha.Iterator;
import java.util.ArrayList;
import java.util.List;
public class BookShelf implements Aggregate{
private List<Book> books;
public BookShelf(){
books = new ArrayList<Book>();
}
public Book getBookAt(int index){
return books.get(index);
}
public void appendBook(Book book){
books.add(book);
}
public int getLength(){
return books.size();
}
@Override
public Iterator createIterator() {
return new BookShelfIterator(this);
}
}
BookShelfIterator
bookshelf对应的迭代器,index代表的当前的索引
有一个bookshelf变量,就是确切的集合(这里就可以用泛型了,可能Util下的iterator就是这样实现的,我还没看)
package com.cutezha.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;
}else {
return false;
}
}
@Override
public Object next() {
Book book = bookShelf.getBookAt(index);
index++;
return book;
}
}
IteratorMain
进行测试
package com.cutezha.Iterator;
public class IteratorMain {
public static void main(String[] args) {
BookShelf bookShelf = new BookShelf();
bookShelf.appendBook(new Book("book1"));
bookShelf.appendBook(new Book("book2"));
bookShelf.appendBook(new Book("book3"));
bookShelf.appendBook(new Book("book4"));
Iterator it = bookShelf.createIterator();
while (it.hasNext()){
Book book = (Book) it.next();
System.out.println(book.getName());
}
}
}
思考与总结
为何要引入Iterator,直接遍历不好吗?
答:引入了迭代器模式,将循环与集合其实是分开了,我们发现在迭代器模式中,遍历这个过程只涉及了Iterator的hasNext与next,也就是说,集合的改动与最终循环的语句是无关的。当其中的组件发生改变的时候,另外的组件不需要改变或者只需要少量的修改。
使用BookShelfIterator与BookShelf就可以达到目的了,为什么还要Aggregate与Iterator这两个接口?
答:关键词,oop的多态性,不要忘了,我们当以面向对象的思想去编程,有了这两个接口,就可以写出不同的集合和迭代器。
最终汇总一下:
迭代器模式的两个关键:集合、迭代器
集合:存储的元素,创建其相应的迭代器
迭代器:对其对应的集合进行遍历
也就是一开始的一句话概述:使用迭代器一个个的遍历出集合中的元素