迭代器模式(Iterator Pattern)是 Java 和 .Net 编程环境中非常常用的设计模式。这种模式用于顺序访问集合对象的元素,不需要知道集合对象的底层表示。
UML图:

从UML图可以看出,需要一个迭代器接口(Iterator),主要两个方法用于遍历集合,而Container主要返回迭代器。
Iterator类:

Container类:

NameRepository类:

TestDemo类:

应用场景:非常适用于不同数据结构的集合,如ArrayList和LinkedList。
网友评论