迭代器模式(Iterator Pattern)是 非常常用的设计模式。
用于顺序访问集合对象的元素,不需要知道集合对象的底层表示。
迭代器模式属于行为型模式。
示例:
Iterator.java
package com.test.dp.iterator;
//迭代器实现的接口
public interface Iterator {
public abstract boolean hasNext();//是否存在下一个
public abstract Object next();//获取下一个
}
Aggregate.java
package com.test.dp.iterator;
//生成迭代器的接口
public interface Aggregate {
public abstract Iterator iterator();//迭代器
}
Book.java
package com.test.dp.iterator;
//书籍
public class Book {
private String name;
public Book(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
BookShelf.java
package com.test.dp.iterator;
//书架,代表集合
public class BookShelf implements Aggregate {
private Book[] books;
private int last = 0;
public BookShelf(int maxsize) {
this.books = new Book[maxsize];
}
public Book 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.java
package com.test.dp.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;
}
}
Main.java
package com.test.dp.iterator;
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("《java编程思想》"));
bookShelf.appendBook(new Book("《线性代数》"));
Iterator it = bookShelf.iterator();
while(it.hasNext()) {
Book book = (Book) it.next();
System.out.println("书名:" + book.getName());
}
}
}
输出结果为:
书名:《编译原理》
书名:《高等数学》
书名:《java编程思想》
书名:《线性代数》
总结:
缺点:由于迭代器模式将存储数据和遍历数据的职责分离,增加新的聚合类需要对应增加新的迭代器类,类的个数成对增加,这在一定程度上增加了系统的复杂性。
使用场景: 1、访问一个聚合对象的内容而无须暴露它的内部表示。 2、需要为聚合对象提供多种遍历方式。 3、为遍历不同的聚合结构提供一个统一的接口。
注意事项:迭代器模式就是分离了集合对象的遍历行为,抽象出一个迭代器类来负责,这样既可以做到不暴露集合的内部结构,又可让外部代码透明地访问集合内部的数据。