迭代器(iterator)模式
该模式用于在数据集合中按照顺序遍历集合
迭代器模式下的四个部分
- Iterator(迭代器)——负责定义按顺序逐个遍历元素的接口
- ConcrereIterator(具体的迭代器)——负责实现Iterator的接口
- Aggregate(集合)——定义创建Iterator角色的接口
- ConcreteAggregate(具体的集合)——负责实现Aggregate接口定义的接口
菜鸟教程上的示例图
示例代码
Aggregate
//集合接口
public interface Aggregate {
Iterator iterator();
}
Iterator
//迭代器接口
public interface Iterator {
boolean hasNext();
Object next();
}
Book
public class Book {
private String name;
public Book(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
BookShelf(ConcreteAggregate)
import java.util.ArrayList;
import java.util.List;
//详细集合类
public class BookShelf implements Aggregate{
private List<Book> books;
public Bookshelf() {
this.books = new ArrayList<Book>();
}
public Book getBookAt(int index) {
return books.get(index);
}
public void appendBook(Book book) {
this.books.add(book);
}
public int getLength(){
return this.books.size();
}
@Override
public Iterator iterator() {
return new BookShelfIterator(this);
}
}
BookShelfIterator(ConcreteIterator)
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(){
return index < this.bookshelf.getLength();
}
@Override
public Object next(){
Book book = this.bookshelf.getBookAt(index);
index++;
return book;
}
}
Main
public class Main {
public static void main(String[] args) {
Bookshelf bookshelf = new Bookshelf();
bookshelf.appendBook(new Book("没伞的孩子只能努力奔跑"));
bookshelf.appendBook(new Book("但是一旦成功,那就是会当临绝顶,一览众山小"));
Iterator iterator = bookshelf.iterator();
while (iterator.hasNext()) {
Book book = (Book)iterator.next();
System.out.println(book.getName());
}
}
}