Computer Science Design Patterns/Iterator

{{Computer Science Design Patterns/Page Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.
 * mode={{{mode|reading}}}
 * page={{{page|{{SUBPAGENAME}}}}}
 * stage=25
 * stage date=14 Feb, 2014
 * stage comment=Add more illustrations.
 * previous=Interpreter
 * next=Mediator
 * content=

Examples
In Java, the interface  is an implementation of the iterator pattern. That way, all the objects that implement the  interface don't need a handy implementation of this pattern.

Cost
This pattern has a cost. Only implement this pattern for an important amount of code. IDE refactoring can't help you much.

Creation
This pattern has a cost to create.

Maintenance
This pattern is easy to maintain.

Removal
This pattern has a cost to remove too.

Advises

 * Put the iterator term in the name of the iterator class to indicate the use of the pattern to the other developers.

Implementations
Java has the Iterator interface.

A simple example showing how to return integers between [start, end] using an

As of Java 5, objects implementing the interface, which returns an   from its only method, can be traversed using Java's foreach loop syntax. The interface from the Java collections framework extends.

Example of class  implementing the   interface:

The class  demonstrates the use of class   : Output:

Here is another example in Java:

Two different usage examples:

JavaScript, as part of ECMAScript 6, supports the iterator pattern with any object that provides a  method, which returns an object with two specific properties:   and. Here's an example that shows a reverse array iterator:

Most of the time, though, it is desirable to provide Iterator semantics on objects so that they can be iterated automatically via  loops. Some of JavaScript's built-in types such as,  , or   already define their own iteration behavior. The same effect can be achieved by defining an object's meta  method, also referred to by. This creates an Iterable object.

Here's an example of a range function that generates a list of values starting from  to , exclusive, using a regular   loop to generate the numbers:

The iteration mechanism of built-in types, like strings, can also be manipulated:

.NET Framework has special interfaces that support a simple iteration:  over a non-generic collection and   over a generic collection.

C# statement  is designed to easily iterate through the collection that implements   and/or   interface. Since C# v2,  is also able to iterate through types that implement   and

Example of using  statement:

Here is another example in C#:

PHP supports the iterator pattern via the Iterator interface, as part of the standard distribution. Objects that implement the interface can be iterated over with the  language construct.

Example of patterns using PHP:

Output
string(15) "Design Patterns" string(16) "PHP7 is the best" string(13) "Laravel Rules" string(9) "DHH Rules"

Another example: As a default behavior in PHP 5, using an object in a foreach structure will traverse all public values. Multiple Iterator classes are available with PHP to allow you to iterate through common lists, such as directories, XML structures and recursive arrays. It's possible to define your own Iterator classes by implementing the Iterator interface, which will override the default behavior. The Iterator interface definition: These methods are all being used in a complete  sequence. The methods are executed in the following order: According to Zend, the  method is called before and after the valid method.

In Perl, objects providing an iterator interface either overload the  (iterator operator), or provide a hash or tied hash interface that can be iterated over with. Both  and   return   when iteration is complete. Overloaded <> operator: Iterating over a hash (or tied hash):

Python prescribes a syntax for iterators as part of the language itself, so that language keywords such as  work with what Python calls iterables. An iterable has an  method that returns an iterator object. The "iterator protocol" requires  return the next element or raise a   exception upon reaching the end of the sequence. Iterators also provide an  method returning themselves so that they can also be iterated over; e.g., using a   loop. Generators are available since 2.2.

In Python 3,  was renamed.

In Python, iterators are objects that adhere to the iterator protocol. You can get an iterator from any sequence (i.e. collection: lists, tuples, dictionaries, sets, etc.) with the  method. Another way to get an iterator is to create a generator, which is a kind of iterator. To get the next element from an iterator, you use the  method (Python 2) /   function (Python 3). When there are no more elements, it raises the  exception. To implement your own iterator, you just need an object that implements the  method (Python 2) /   method (Python 3). Here are two use cases:

Raku provides APIs for iterators, as part of the language itself, for objects that can be iterated with  and related iteration constructs, like assignment to a   variable. An iterable must at least implement an  method that returns an iterator object. The "iterator protocol" requires the  method to return the next element if possible, or return the sentinel value   if no more values could be produced. The iteration APIs is provided by composing the  role, , or both, and implementing the required methods.

To check if a type object or an object instance is iterable, the  method can be used:

The  method returns   if and only if the invocant conforms to the argument type.

Here's an example of a  subroutine that mimics Python's   function:

MATLAB supports both external and internal implicit iteration using either "native" arrays or  arrays. In the case of external iteration where the onus is on the user to advance the traversal and request next elements, one can define a set of elements within an array storage structure and traverse the elements using the -loop construct. For example, traverses an array of integers using the  keyword. In the case of internal iteration where the user can supply an operation to the iterator to perform over every element of a collection, many built-in operators and MATLAB functions are overloaded to execute over every element of an array and return a corresponding output array implicitly. Furthermore, the  and   functions can be leveraged for performing custom or user defined operations over "native" arrays and   arrays respectively. For example, defines a primary function  which implicitly applies custom subfunction   to each element of an array using built-in function. Alternatively, it may be desirable to abstract the mechanisms of the array storage container from the user by defining a custom object-oriented MATLAB implementation of the Iterator Pattern. Such an implementation supporting external iteration is demonstrated in MATLAB Central File Exchange item Design Pattern: Iterator (Behavioural). This is written in the new class-definition syntax introduced with MATLAB software version 7.6 (R2008a) and features a one-dimensional  array realisation of the List Abstract Data Type (ADT) as the mechanism for storing a heterogeneous (in data type) set of elements. It provides the functionality for explicit forward List traversal with the,   and   methods for use in a  -loop.