Iterator模式

使用java语言显示数组arr中的元素时,我们可以使用下面这样的for循环遍历数组

1
2
3
for (int i = 0; i < arr.length; i++) {
System.out.printlf(arr[i]);
}

循环变量 i 初始值为0,随后会递增为1,2,3…,每次循环都会输出 arr[i]
将循环变量 i 抽象化、通用化后形成的模式,在设计模式中称为 Iterator模式

  • Iterator模式用于在数据集合中按照顺序遍历集合。
  • Iterator有反复做某事的意思,汉语称为“迭代器

示例代码

Aggregate

1
2
3
public interface Aggregate {
public abstract Iterator iterator();
}

Book

1
2
3
4
5
6
7
8
9
public class Book {
private String name;
public Book(String name) {
this.name = name;
}
public String getName() {
return name;
}
}

BookShelf

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import java.util.ArrayList;

public class BookShelf implements Aggregate {
private ArrayList books;
public BookShelf(int initialsize) {
this.books = new ArrayList(initialsize);
}
public Book getBookAt(int index) {
return (Book)books.get(index);
}
public void appendBook(Book book) {
books.add(book);
}
public int getLength() {
return books.size();
}
public Iterator iterator() {
return new BookShelfIterator(this);
}
}

BookShelfIterator

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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;
}
}

Iterator

1
2
3
4
public interface Iterator {
public abstract boolean hasNext();
public abstract Object next();
}

Main

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import java.util.*;

public class Main {
public static void main(String[] args) {
BookShelf bookShelf = new BookShelf(4);
bookShelf.appendBook(new Book("Around the World in 80 Days"));
bookShelf.appendBook(new Book("Bible"));
bookShelf.appendBook(new Book("Cinderella"));
bookShelf.appendBook(new Book("Daddy-Long-Legs"));
bookShelf.appendBook(new Book("East of Eden"));
bookShelf.appendBook(new Book("Frankenstein"));
bookShelf.appendBook(new Book("Gulliver's Travels"));
bookShelf.appendBook(new Book("Hamlet"));
Iterator it = bookShelf.iterator();
while (it.hasNext()) {
Book book = (Book)it.next();
System.out.println(book.getName());
}
}
}