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 int m_nID;
- private string m_strName;
- public Employee(int nID,string strName)
- {
- m_nID = nID;
- m_strName = strName;
- }
- #region Property
-
-
-
- public int EmployeeID
- {
- get
- {
- return this.m_nID;
- }
- }
-
-
-
- public string EmployeeName
- {
- get
- {
- return this.m_strName;
- }
- }
- # endregion
- }
I have two more classes
-
EmployeeList, which is derived from the interface IEnumerable. So this class should implement GetEnumerator function. This function returns an object of EnumerateEmployee which is derived from IEnumerator.
-
EnumerateEmployee, which is derived from the interface IEnumerator. So this class should implement two functions namely MoveNext and Reset and a property called Current. In this class I created four objects of Employee objects and added to an array list. MoveNext function will iterate through this collection.
- public class EnumerateEmployee: IEnumerator
- {
- private int m_nPosition;
- private ArrayList m_ArrEmployee = new ArrayList();
-
-
-
- public EnumerateEmployee()
- {
- 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"));
- }
- #region EnumMembers
-
-
-
-
- public bool MoveNext()
- {
- bool b_return = false;
- ++m_nPosition;
- if(m_nPosition < m_ArrEmployee.Count)
- b_return = true;
- return b_return;
- }
-
-
-
- public object Current
- {
- get
- {
- return m_ArrEmployee[m_nPosition];
- }
- }
-
-
-
- public void Reset()
- {
- m_nPosition = -1;
- }
- # endregion
- }
In order to execute this class, create a window application and put the following code in the button click event.
- string strName;
- int nID;
- EmployeeList objEmpList = new EmployeeList();
- IEnumerator objEnumEmp = objEmpList.GetEnumerator();
-
- while(objEnumEmp.MoveNext())
- {
- Employee objEmployee = (Employee)objEnumEmp.Current;
- nID = objEmployee.EmployeeID; strName = objEmployee.EmployeeName;
- }