Java设计模式之迭代器模式详解 - 详解
2025-10-05 18:16 tlnshuju 阅读(35) 评论(0) 收藏 举报Java设计模式之迭代器模式详解
一、迭代器模式核心思想
核心目标:提供一种方法顺序访问聚合对象中的元素,而不暴露其内部实现。如同导游带领游客参观景点,游客无需知道景点的组织方式,只需跟随导游即可遍历所有景点。
二、迭代器模式类图(Mermaid)
三、代码实现示例
1. 自定义集合迭代器
// 迭代器接口
interface Iterator<
T> {
boolean hasNext(
)
;
T next(
)
;
void remove(
)
;
}
// 聚合接口
interface IterableCollection<
T> {
Iterator<
T> createIterator(
)
;
}
// 具体集合:书架
class BookShelf
implements IterableCollection<
Book> {
private List<
Book> books =
new ArrayList<
>(
)
;
public
void addBook(Book book) {
books.add(book)
;
}
public Book getBook(
int index) {
return books.get(index)
;
}
public
int size(
) {
return books.size(
)
;
}
@Override
public Iterator<
Book> createIterator(
) {
return
new BookShelfIterator(
this
)
;
}
}
// 具体迭代器
class BookShelfIterator
implements Iterator<
Book> {
private BookShelf bookShelf;
private
int position;
public BookShelfIterator(BookShelf bookShelf) {
this.bookShelf = bookShelf;
this.position = 0
;
}
@Override
public
boolean hasNext(
) {
return position < bookShelf.size(
)
;
}
@Override
public Book next(
) {
Book book = bookShelf.getBook(position)
;
position++
;
return book;
}
@Override
public
void remove(
) {
throw
new UnsupportedOperationException(
)
;
}
}
// 书籍类
class Book {
private String title;
public Book(String title) {
this.title = title;
}
public String getTitle(
) {
return title;
}
}
// 客户端调用
public
class Client {
public
static
void main(String[] args) {
BookShelf shelf =
new BookShelf(
)
;
shelf.addBook(
new Book("设计模式"
)
)
;
shelf.addBook(
new Book("Java核心技术"
)
)
;
shelf.addBook(
new Book("算法导论"
)
)
;
Iterator<
Book> it = shelf.createIterator(
)
;
while (it.hasNext(
)
) {
System.out.println(it.next(
).getTitle(
)
)
;
}
/* 输出:
设计模式
Java核心技术
算法导论 */
}
}
四、模式优缺点分析
✅ 优势
- 解耦集合与遍历:客户端无需知道集合内部结构
- 支持多种遍历方式:可定义不同迭代器(正序/逆序/过滤等)
- 单一职责原则:集合管理数据,迭代器负责遍历
- 并行遍历:支持多迭代器同时操作
❌ 缺点
- 简单集合不适用:对小型集合可能过度设计
- 性能开销:迭代器对象创建成本
- 修改集合风险:遍历时修改集合可能导致异常
五、典型应用场景
- 集合框架:Java的List、Set、Map迭代器
- 树形结构遍历:二叉树/BFS/DFS迭代器
- 数据库查询:ResultSet遍历
- 文件系统:目录递归遍历
- 社交网络:好友关系遍历
- 游戏地图:网格单元遍历
六、Mermaid序列图(迭代过程)
七、迭代器模式 vs 其他模式
| 对比模式 | 核心区别 |
|---|---|
| 访问者模式 | 对集合元素执行操作,不控制遍历顺序 |
| 组合模式 | 处理树形结构,迭代器可遍历组合 |
| 工厂方法 | 用于创建迭代器对象 |
八、Java集合框架中的迭代器
Java迭代器层次结构
九、高级应用技巧
1. 过滤迭代器(只返回符合条件的元素)
class FilterIterator<
T>
implements Iterator<
T> {
private Iterator<
T> source;
private Predicate<
T> filter;
private T nextItem;
public FilterIterator(Iterator<
T> source, Predicate<
T> filter) {
this.source = source;
this.filter = filter;
findNext(
)
;
}
private
void findNext(
) {
nextItem =
null
;
while (source.hasNext(
)
) {
T item = source.next(
)
;
if (filter.test(item)
) {
nextItem = item;
break
;
}
}
}
public
boolean hasNext(
) {
return nextItem !=
null
;
}
public T next(
) {
T result = nextItem;
findNext(
)
;
return result;
}
}
// 使用示例
Iterator<
Book> it =
new FilterIterator<
>(
shelf.createIterator(
)
,
book -> book.getTitle(
).contains("Java"
)
)
;
2. 并发安全迭代器
class ConcurrentIterator<
T>
implements Iterator<
T> {
private
final List<
T> snapshot;
private
int position;
public ConcurrentIterator(Collection<
T> collection) {
this.snapshot =
new ArrayList<
>(collection)
;
// 创建快照
}
public
boolean hasNext(
) {
return position < snapshot.size(
)
;
}
public T next(
) {
return snapshot.get(position++
)
;
}
}
十、实际框架应用案例
Spring Data的Repository迭代
Iterable<
User> users = userRepository.findAll(
)
;
Iterator<
User> it = users.iterator(
)
;
while (it.hasNext(
)
) {
User user = it.next(
)
;
// 处理用户
}
Java Stream API(内部使用迭代器)
List<
String> names = Arrays.asList("Alice"
, "Bob"
, "Charlie"
)
;
names.stream(
)
.filter(name -> name.length(
) >
4
)
.forEach(System.out::println
)
;
十一、常见问题解答
Q1:如何在遍历时安全删除元素?
使用迭代器的remove()方法:
Iterator<
Book> it = shelf.createIterator(
)
;
while (it.hasNext(
)
) {
Book book = it.next(
)
;
if (book.getTitle(
).contains("过期"
)
) {
it.remove(
)
;
// 安全删除
}
}
Q2:如何实现双向遍历?
使用ListIterator:
ListIterator<
Book> it = books.listIterator(
)
;
it.next(
)
;
// 正向遍历
it.previous(
)
;
// 返回上一个
it.add(newBook)
;
// 添加元素
Q3:迭代器模式如何支持并行遍历?
// 创建多个独立迭代器
Iterator<
Book> it1 = shelf.createIterator(
)
;
Iterator<
Book> it2 = shelf.createIterator(
)
;
// 线程1使用it1遍历
// 线程2使用it2遍历
如果你觉得文章对你有帮助的话,帮忙点个关注吧!谢谢啦
浙公网安备 33010602011771号