Iterator pattern:
In object-oriented programming, the Iterator pattern is a design pattern in which iterators are used to aggregate object sequentially without exposing its underlying representation. An Iterator object encapsulates the internal structure of how the iteration occurs.
This article, explains how to use the Iterator pattern to manipulate any collection of objects. To explain this I am using two interfaces IEnumerator and IEnumerables.
I have a class called Employee, which stores his ID and name.
Public Class Employee
Private m_nID As Integer
Private m_strName As String
Public Sub New(ByVal nID As Integer, ByVal strName As String)
m_nID = nID
m_strName = strName
End Sub
Public ReadOnly Property EmployeeID() As Integer
Get
Return Me.m_nID
End Get
End Property
Public ReadOnly Property EmployeeName() As String
Get
Return Me.m_strName
End Get
End Property
End Class
Public Class EnumerateEmployee
Implements IEnumerator
Private m_nPosition As Integer
Private m_ArrEmployee As ArrayList = New ArrayList
Public Sub New()
m_nPosition = -1
m_ArrEmployee.Add(New Employee(1, "Kamsa"))
m_ArrEmployee.Add(New Employee(2, "Rama"))
m_ArrEmployee.Add(New Employee(3, "Sita"))
m_ArrEmployee.Add(New Employee(4, "Gopala"))
End Sub
Public Function MoveNext() As Boolean
Dim b_return As Boolean = False
System.Threading.Interlocked.Increment(m_nPosition)
If m_nPosition < m_ArrEmployee.Count Then
b_return = True
End If
Return b_return
End Function
Public ReadOnly Property Current() As Object
Get
Return m_ArrEmployee(m_nPosition)
End Get
End Property
Public Sub Reset()
m_nPosition = -1
End Sub
End Class
In order to execute this class, create a window application and put the following code in the button click event.