Iterator pattern
   HOME

TheInfoList



OR:

In
object-oriented programming Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects", which can contain data and code. The data is in the form of fields (often known as attributes or ''properties''), and the code is in the form of ...
, the iterator pattern is a
design pattern A design pattern is the re-usable form of a solution to a design problem. The idea was introduced by the architect Christopher Alexander and has been adapted for various other disciplines, particularly software engineering. The "Gang of Four" boo ...
in which an
iterator In computer programming, an iterator is an object that enables a programmer to traverse a container, particularly lists. Various types of iterators are often provided via a container's interface. Though the interface and semantics of a given iterat ...
is used to traverse a
container A container is any receptacle or enclosure for holding a product used in storage, packaging, and transportation, including shipping. Things kept inside of a container are protected on several sides by being inside of its structure. The term ...
and access the container's elements. The iterator pattern decouples
algorithm In mathematics and computer science, an algorithm () is a finite sequence of rigorous instructions, typically used to solve a class of specific problems or to perform a computation. Algorithms are used as specifications for performing ...
s from containers; in some cases, algorithms are necessarily container-specific and thus cannot be decoupled. For example, the hypothetical algorithm ''SearchForElement'' can be implemented generally using a specified type of iterator rather than implementing it as a container-specific algorithm. This allows ''SearchForElement'' to be used on any container that supports the required type of iterator.


Overview

The Iterator design pattern is one of the twenty-three well-known '' GoF design patterns'' that describe how to solve recurring design problems to design flexible and reusable object-oriented software, that is, objects that are easier to implement, change, test, and reuse.


What problems can the Iterator design pattern solve?

* The elements of an aggregate object should be accessed and traversed without exposing its representation (data structures). * New traversal operations should be defined for an aggregate object without changing its interface. Defining access and traversal operations in the aggregate interface is inflexible because it commits the aggregate to particular access and traversal operations and makes it impossible to add new operations later without having to change the aggregate interface.


What solution does the Iterator design pattern describe?

* Define a separate (iterator) object that encapsulates accessing and traversing an aggregate object. * Clients use an iterator to access and traverse an aggregate without knowing its representation (data structures). Different iterators can be used to access and traverse an aggregate in different ways.
New access and traversal operations can be defined independently by defining new iterators. See also the UML class and sequence diagram below.


Definition

The essence of the Iterator Pattern is to "Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.".


Structure


UML class and sequence diagram

In the above
UML The Unified Modeling Language (UML) is a general-purpose, developmental modeling language in the field of software engineering that is intended to provide a standard way to visualize the design of a system. The creation of UML was originally m ...
class diagram In software engineering, a class diagram in the Unified Modeling Language (UML) is a type of static structure diagram that describes the structure of a system by showing the system's classes, their attributes, operations (or methods), and the rela ...
, the Client class refers (1) to the Aggregate interface for creating an Iterator object (createIterator()) and (2) to the Iterator interface for traversing an Aggregate object (next(),hasNext()). The Iterator1 class implements the Iterator interface by accessing the Aggregate1 class. The
UML The Unified Modeling Language (UML) is a general-purpose, developmental modeling language in the field of software engineering that is intended to provide a standard way to visualize the design of a system. The creation of UML was originally m ...
sequence diagram A sequence diagram or system sequence diagram (SSD) shows process interactions arranged in time sequence in the field of software engineering. It depicts the processes involved and the sequence of messages exchanged between the processes needed ...
shows the run-time interactions: The Client object calls createIterator() on an Aggregate1 object, which creates an Iterator1 object and returns it to the Client. The Client uses then Iterator1 to traverse the elements of the Aggregate1 object.


UML class diagram


Language-specific implementation

Some languages standardize syntax. C++ and Python are notable examples.


C#

.NET Framework The .NET Framework (pronounced as "''dot net"'') is a proprietary software framework developed by Microsoft that runs primarily on Microsoft Windows. It was the predominant implementation of the Common Language Infrastructure (CLI) until bein ...
has special interfaces that support a simple iteration: System.Collections.IEnumerator over a non-generic collection and System.Collections.Generic.IEnumerator over a generic collection. C# statement foreach is designed to easily iterate through the collection that implements System.Collections.IEnumerator and/or System.Collections.Generic.IEnumerator interface. Since C# v2, foreach is also able to iterate through types that implement System.Collections.Generic.IEnumerable and System.Collections.Generic.IEnumerator Example of using foreach statement: var primes = new List; long m = 1; foreach (var prime in primes) m *= prime;


C++

C++ C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
implements iterators with the semantics of pointers in that language. In C++, a class can overload all of the pointer operations, so an iterator can be implemented that acts more or less like a pointer, complete with dereference, increment, and decrement. This has the advantage that C++ algorithms such as std::sort can immediately be applied to plain old memory buffers, and that there is no new syntax to learn. However, it requires an "end" iterator to test for equality, rather than allowing an iterator to know that it has reached the end. In C++ language, we say that an iterator models the iterator
concept Concepts are defined as abstract ideas. They are understood to be the fundamental building blocks of the concept behind principles, thoughts and beliefs. They play an important role in all aspects of cognition. As such, concepts are studied by ...
.


Java

Java has the interface. A simple example showing how to return integers between tart, endusing an Iterator import java.util.Iterator; import java.util.NoSuchElementException; public class RangeIteratorExample As of Java 5, objects implementing the interface, which returns an Iterator from its only method, can be traversed using Java's foreach loop syntax. The interface from the
Java collections framework The Java collections framework is a set of classes and interfaces that implement commonly reusable collection data structures. Although referred to as a framework, it works in a manner of a library. The collections framework provides both interf ...
extends Iterable. Example of class Family implementing the Iterable interface: import java.util.Iterator; import java.util.Set; class Family implements Iterable The class IterableExample demonstrates the use of class Family : public class IterableExample Output: Ron Weasley Molly Weasley Percy Weasley Fred Weasley Charlie Weasley George Weasley Arthur Weasley Ginny Weasley Bill Weasley


JavaScript

JavaScript JavaScript (), often abbreviated as JS, is a programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. As of 2022, 98% of websites use JavaScript on the client side for webpage behavior, of ...
, as part of ECMAScript 6, supports the iterator pattern with any object that provides a next() method, which returns an object with two specific properties: done and value. Here's an example that shows a reverse array iterator: function reverseArrayIterator(array) const it = reverseArrayIterator( three', 'two', 'one'; console.log(it.next().value); //-> 'one' console.log(it.next().value); //-> 'two' console.log(it.next().value); //-> 'three' console.log(`Are you done? $`); //-> true Most of the time, though, it is desirable to provide Iterator semantics on objects so that they can be iterated automatically via for...of loops. Some of JavaScript's built-in types such as Array, Map, or Set already define their own iteration behavior. The same effect can be achieved by defining an object's meta @@iterator method, also referred to by Symbol.iterator. This creates an Iterable object. Here's an example of a range function that generates a list of values starting from start to end, exclusive, using a regular for loop to generate the numbers: function range(start, end) for (number of range(1, 5)) The iteration mechanism of built-in types, like strings, can also be manipulated: let iter = I', 't', 'e', 'r', 'a', 't', 'o', 'r'Symbol.iterator](); iter.next().value; //-> I iter.next().value; //-> t


PHP

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 foreach language construct. Example of patterns using PHP: addTitle('Design Patterns'); $booksCollection->addTitle('PHP7 is the best'); $booksCollection->addTitle('Laravel Rules'); $booksCollection->addTitle('DHH Rules'); foreach ($booksCollection as $book)


Output

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


Python

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


Raku

Raku provides APIs for iterators, as part of the language itself, for objects that can be iterated with for and related iteration constructs, like assignment to a Positional variable. An iterable must at least implement an iterator method that returns an iterator object. The "iterator protocol" requires the pull-one method to return the next element if possible, or return the sentinel value IterationEnd if no more values could be produced. The iteration APIs is provided by composing the Iterable role, Iterator, or both, and implementing the required methods. To check if a type object or an object instance is iterable, the does method can be used: say Array.does(Iterable); #=> True say , 2, 3does(Iterable); #=> True say Str.does(Iterable); #=> False say "Hello".does(Iterable); #=> False The does method returns True if and only if the invocant conforms to the argument type. Here's an example of a range subroutine that mimics Python's range function: multi range(Int:D $start, Int:D $end where * <= $start, Int:D $step where * < 0 = -1) multi range(Int:D $start, Int:D $end where * >= $start, Int:D $step where * > 0 = 1) my \x = range(1, 5); .say for x; # OUTPUT: # 1 # 2 # 3 # 4 say x.map(* ** 2).sum; # OUTPUT: # 30 my \y = range(-1, -5); .say for y; # OUTPUT: # -1 # -2 # -3 # -4 say y.map(* ** 2).sum; # OUTPUT: # 30


See also

*
Composite pattern In software engineering, the composite pattern is a partitioning design pattern. The composite pattern describes a group of objects that are treated the same way as a single instance of the same type of object. The intent of a composite is to "comp ...
*
Container (data structure) In computer programming, a collection is a grouping of some variable number of data items (possibly zero) that have some shared significance to the problem being solved and need to be operated upon together in some controlled fashion. Generally, ...
*
Design pattern (computer science) In software engineering, a software design pattern is a general, reusable solution to a commonly occurring problem within a given context in software design. It is not a finished design that can be transformed directly into source or machine cod ...
*
Iterator In computer programming, an iterator is an object that enables a programmer to traverse a container, particularly lists. Various types of iterators are often provided via a container's interface. Though the interface and semantics of a given iterat ...
*
Observer pattern In software design and engineering, the observer pattern is a software design pattern in which an object, named the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by ca ...


References


External links


Object iteration
in PHP
Iterator Pattern
in C#
Iterator pattern in UML and in LePUS3 (a formal modelling language)

SourceMaking tutorial



Iterator Pattern
{{Design Patterns Patterns Articles with example C++ code Articles with example C Sharp code Articles with example JavaScript code Articles with example Perl code Articles with example PHP code Iteration in programming Software design patterns