Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikipediaThe Free Encyclopedia
Search

Iterator pattern

From Wikipedia, the free encyclopedia
Software design pattern

Inobject-oriented programming, theiterator pattern is adesign pattern in which aniterator is used to traverse acontainer and access the container's elements. The iterator pattern decouplesalgorithms from containers; in some cases, algorithms are necessarily container-specific and thus cannot be decoupled.

For example, the hypothetical algorithmSearchForElement can be implemented generally using a specified type of iterator rather than implementing it as a container-specific algorithm. This allowsSearchForElement to be used on any container that supports the required type of iterator.

Overview

[edit]

The Iterator[1]design pattern is one of the 23 well-known"Gang of Four" 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?

[edit]

[2]

  • 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 operationslater without having to change the aggregate interface.

What solution does the Iterator design pattern describe?

[edit]
  • 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

[edit]

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.".[3]

Structure

[edit]

UML class and sequence diagram

[edit]
A sample UML class and sequence diagram for the Iterator design pattern.[4]

In the aboveUMLclass diagram, theClient class refers (1) to theAggregate interface for creating anIterator object (createIterator()) and (2) to theIterator interface for traversing anAggregate object (next(),hasNext()).TheIterator1 class implements theIterator interface by accessing theAggregate1 class.

TheUMLsequence diagramshows the run-time interactions: TheClient object callscreateIterator() on anAggregate1 object, which creates anIterator1 object and returns itto theClient.TheClient uses thenIterator1 to traverse the elements of theAggregate1 object.

UML class diagram

[edit]
The iterator pattern

Example

[edit]
Main article:Iterator

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

C++

[edit]

C++ implements iterators with the semantics ofpointers 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 asstd::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 iteratorconcept.

This C++11 implementation is based on chapter "Generalizing vector yet again".[5]

#include<iostream>#include<stdexcept>#include<initializer_list>classVector{public:usingiterator=double*;iteratorbegin(){returnelem;}iteratorend(){returnelem+sz;}Vector(std::initializer_list<double>lst):elem(nullptr),sz(0){sz=lst.size();elem=newdouble[sz];double*p=elem;for(autoi=lst.begin();i!=lst.end();++i,++p){*p=*i;}}~Vector(){delete[]elem;}intsize()const{returnsz;}double&operator[](intn){if(n<0||n>=sz)throwstd::out_of_range("Vector::operator[]");returnelem[n];}Vector(constVector&)=delete;// rule of threeVector&operator=(constVector&)=delete;private:double*elem;intsz;};intmain(){Vectorv={1.1*1.1,2.2*2.2};for(constauto&x:v){std::cout<<x<<'\n';}for(autoi=v.begin();i!=v.end();++i){std::cout<<*i<<'\n';}for(autoi=0;i<=v.size();++i){std::cout<<v[i]<<'\n';}}

The program output is

1.214.841.214.841.214.84terminatecalledafterthrowinganinstanceof'std::out_of_range'what():Vector::operator[]

See also

[edit]

References

[edit]
  1. ^Erich Gamma; Richard Helm; Ralph Johnson; John Vlissides (1994).Design Patterns: Elements of Reusable Object-Oriented Software. Addison Wesley. pp. 257ff.ISBN 0-201-63361-2.
  2. ^"The Iterator design pattern - Problem, Solution, and Applicability".w3sDesign.com. Retrieved2017-08-12.
  3. ^Gang Of Four
  4. ^"The Iterator design pattern - Structure and Collaboration".w3sDesign.com. Retrieved2017-08-12.
  5. ^Bjarne Stroustrup (2014).Programming: Principles and Practice using C++ (2 ed.). Addison Wesley. pp. 729 ff.ISBN 978-0-321-99278-9.

External links

[edit]
Gang of Four
patterns
Creational
Structural
Behavioral
Concurrency
patterns
Architectural
patterns
Other
patterns
Books
People
Communities
See also
Retrieved from "https://en.wikipedia.org/w/index.php?title=Iterator_pattern&oldid=1246079515"
Categories:
Hidden categories:

[8]ページ先頭

©2009-2025 Movatter.jp