Iterator

The Iterator is one of the simplest and most frequently used of the
design patterns. The Iterator pattern allows you to move through a list or
collection of data using a standard interface without having to know the
details of the internal representations of that data. In addition you can also
define special iterators that perform some special processing and return only
specified elements of the data collection.

In object-oriented programming, the Iterator pattern is a design pattern in which iterators are used to access the elements of an aggregate object sequentially without exposing its underlying representation. An Iterator object encapsulates the internal structure of how the iteration occurs.

For example, a tree, linked list, hash table, and an array all need to be iterated with the methods search, sort, and next. Rather than having 12 different methods to manage (one implementation for each of the previous three methods in each structure), using the iterator pattern yields just seven: one for each class using the iterator to obtain the iterator and one for each of the three methods. Therefore, to run the search method on the array, you would call array.search(), which hides the call to array.iterator.search().

 

Structure

 

Iterator in UML

Motivation

The Iterator is useful because it provides a defined way to move
through a set of data elements without exposing how it does it. Since the
Iterator is an interface, you can implement it in any way that is convenient for
the data you are returning.

The Iterator of choice in Java is Java’s built-in Enumeration type.

 

Filtered Iterators

While having a clearly defined method of moving through a
collection is helpful, you can also define filtered Enumerations that perform
some computation on the data before returning it. For example, you could
return the data ordered in some particular way, or only those objects that
match a particular criterion. Then, rather than have a lot of very similar
interfaces for these filtered enumerations, you simply provide a method
which returns each type of enumeration, with each one of these enumerations
having the same methods.

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值