It Erator Pattern
It Erator Pattern
Dr. Neal
CIS 480
Iterator
An iterator pattern can be used when one
class is a collection of things and would
like to provide a standardized method of
accessing its collection to another class.
In Microsofts C# the .NET framework
defines two interfaces for solving the
iterator problem.
Microsoft C# Interfaces
IEnumerable
Defines a method GetEnumerator() which
return a class of type IEnumerator
IEnumerator
Defines methods for MoveNext() and ReSet()
which allow sequential movement through the
collection or reset to the beginning
Defines an attribute/property Current that
contains the current object in the collection
<<Interface>>
IEnumerator
Current : object
GetEnumerator() : IEnumerator
MoveNext() : bool
Reset() : void
<<Interface>>
IEnumerator
<<Interface>>
IEnumerable
(from .NET )
Current : object
Classes
for our
Example
(from .NET )
MoveNext() : bool
Reset() : void
GetEnumerator() : IEnumerator
EnumCart
count : int
list : object[]
Current : object
instantiates
EnumCart(c : object[])
MoveNext() : bool
Reset() : void
uses
Cart
cart : string[]
length : int
Cart()
GetEnumerator() : IEnumerator
instantiates
Form1
btnDumpCart : Button
lblCartEnumeration : Label
lblResults : Label
Form1()
dumpCartClick(o : object, e : Eventargs) : void
Dispose(b : bool) : void
InitializeComponent() : void
Cart
Class
Implemention
of
IEnumerable
Interface
EnumCart
Class
Implemention
of IEnumerator
Interface
A foreach Enumeration in C#
Programmer
Created
Code
C# Compiler
Generated
Code
Resulting
Sequence
Diagram
: Form1
: User
: Cart
1: dumpCartClick(object, Eventargs)
2: Cart( )
Complier
Generated
Code
3: GetEnumerator( )
4: MoveNext( )
5: Current
: EnumCart