Iterator模式用于在数据集合中按照顺序遍历集合。
实例程序:将book放置到书架上,并按顺序显示
【角色说明】
【Iterator】定义按顺序逐个遍历元素的接口(API)
【ConcreteIterator】负责实现Iterator角色所定义的接口。该角色中包含了遍历集合所必需的信息
【Aggregate】负责定义创建Iterator角色的接口。里面定义了iterator方法
【ConcreteAggregate】集合
引入Iterator后可以将遍历和实现分离开
这里只使用了Iterator的hasNext方法和next方法,并没有调用BookShelf的方法,就是说不依赖集合的实现。只要具体的集合的iterator方法能正确的返回Iterator实例,不对while做修改也可以。
“可复用”。
“面对接口编程”
【next方法】返回当前元素,并指向下一个元素
【hasNext方法】确认接下来是否可以调用next方法。
【迭代器的种类多种多样】遍历方法可以从前向后,从后向前或者跳跃式遍历
【不需要deleteIterator】java中,没有被使用的对象实例会被自动删除。
手写迭代器模式的注意点