- Iterator pattern
-
In object-oriented programming, the iterator pattern is a design pattern in which an iterator is used to traverse a container and access the container's elements. The iterator pattern decouples algorithms 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 which supports the required type of iterator.
Contents
Definition
The essence of the Iterator Factory method Pattern is to "Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.".[1]
Language-specific implementation
Main article: IteratorSome languages standardize syntax. C++ and Python are notable examples.
C++
C++ 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.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 sequences. A sequence has an__iter__()
method that returns an iterator object. The "iterator protocol" which requiresnext()
return the next element or raise aStopIteration
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 afor
loop. (In Python 3,next()
was replaced with__next__()
.)[2]Java
Java has an Iterator interface that the Collections should implement in order to transverse the elements of the collection
See also
- Iterator
- Container (data structure)
- Observer pattern
- Composite pattern
- Design pattern (computer science)
References
- ^ Gang Of Four
- ^ "Python v2.7.1 documentation: The Python Standard Library: 5. Built-in Types". http://docs.python.org/library/stdtypes.html. Retrieved 2 May 2011.
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
Creational Structural Behavioral Categories:- Software design patterns
- Articles with example PHP code
- Articles with example C++ code
Wikimedia Foundation. 2010.