本文介绍设计模式中的迭代器模式,首先通俗的解释迭代器模式的基本概念和对应的四个角色,并根据四个角色举一个典型的实例,为了加强知识的连贯性,我们以Jdk源码集合中使用迭代器模式的应用进一步说明,最后说明迭代器模式的应用场景和优缺点。
读者可以拉取完整代码本地学习,实现代码均测试通过上传到码云
一、概念理解
迭代器模式的官方解释是提供一个对象来顺序访问聚合对象中的一系列数据,而不公开聚合对象的内部表示。聚合对象是什么?最典型的是集合类。
[En]
The official interpretation of the iterator pattern is to provide an object to access a series of data in the aggregate object sequentially without exposing the internal representation of the aggregate object. What is the aggregate object? The most typical is the collection class.
换句话说,集合中的数据是私有的,集合不应该提供直接遍历方法,来定义访问集合的新对象。
[En]
In other words, the data in the collection is private, the collection should not provide a direct traversal method, to define a new object to access the collection.
由于它是专用于遍历的对象,即被遍历的聚合对象,因此显然至少有两个对象,迭代器对象和聚合对象,因为它们遵循面向接口的编程原则。迭代器对象和聚合对象应该从接口中抽象出来,因此自然应该有四个角色:
[En]
Since it is an object dedicated to traversal, a traversed aggregate object, it is obvious that there are at least two objects, the iterator object and the aggregation object, because they follow the principle of interface-oriented programming. Iterator objects and aggregation objects should be abstracted out of the interface, so naturally there should be four roles:
抽象聚合(InterfaceAggregate)角色:定义存储、添加、删除聚合元素以及创建迭代器对象的接口。
具体聚合(ConcreteAggregate)角色:实现抽象聚合类,返回一个具体迭代器的实例。
抽象迭代器(Iterator)角色:定义访问和遍历聚合元素的接口,通常包含 hasNext()、next() 等方法。
具体迭代器(Concretelterator)角色:实现抽象迭代器接口中所定义的方法,完成对聚合对象的遍历,记录遍历的当前位置。