Intro

迭代器模式(\(Iterator\)),平常我们接触的最多的一个设计模式,可能很多人没有意识到它其实是一种设计模式,在\(Java\)中,迭代器模式可以很好的帮助我们去遍历集合里面的内容而不用去了解底层的实现。

API设计

我们需要实现以下几个接口和类来完成一个最简单的迭代器模式实现:

名字 说明
Aggregate 表示集合的接口
Iterator 表示遍历集合的接口
Book 表示书(集合内的事物)
BookShelf 表示书架(集合的实现)
BookShelfIterator 书架的迭代器(遍历集合接口实现)

代码实现

# Aggregate

1
2
3
4
5
6
package net.sunzhenyu.miscellaneous.pattern.iterator;

public interface Aggregate {

Iterator iterator();
}

# Iterator

1
2
3
4
5
6
7
8
package net.sunzhenyu.miscellaneous.pattern.iterator;

public interface Iterator {

boolean hasNext();

Object next();
}

# Book

1
2
3
4
5
6
7
8
9
10
11
package net.sunzhenyu.miscellaneous.pattern.iterator.model;

import lombok.AllArgsConstructor;
import lombok.Data;

@Data
@AllArgsConstructor
public class Book {

private String name;
}

# BookShelf

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package net.sunzhenyu.miscellaneous.pattern.iterator;

import net.sunzhenyu.miscellaneous.pattern.iterator.model.Book;

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 Book add(Book book) {
this.books[last] = book;
last++;
return book;
}

public int size() {
return books.length;
}

@Override
public Iterator iterator() {
return null;
}
}

# BookShelfIterator

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package net.sunzhenyu.miscellaneous.pattern.iterator;

import net.sunzhenyu.miscellaneous.pattern.iterator.model.Book;

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 < bookShelf.size();
}

@Override
public Object next() {
Book temp = bookShelf.getBookAt(index);
index++;
return temp;
}
}