Friday, June 7, 2013

Iterator Design Patterns (Behavioral Patterns) in C#

****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.


class Program
    {
        static void Main(string[] args)
        {
            string name;
            int id;
            EmployeeList list = new EmployeeList();
            IEnumerator enumEmp = list.GetEnumerator();
            while (enumEmp.MoveNext())
            {
                Employee emp = (Employee)enumEmp.Current;
                id = emp.Id;
                name = emp.Name;
            }
        }
    }

    public class Employee
    {
        private int _id;
        private string _name;

        public int Id
        {
            get { return _id; }
        }
        public string Name
        {
            get { return _name; }
        }
        public Employee(int id, string name)
        {
            _id = id;
            _name = name;
        }
    }
    public class EnumerateEmployee : IEnumerator
    {
        private int position;
        private ArrayList listEmployee = new ArrayList();
        public EnumerateEmployee()
        {
            position = -1;
            listEmployee.Add(new Employee(1, "abc"));
            listEmployee.Add(new Employee(2, "xyz"));
            listEmployee.Add(new Employee(3, "abc11"));
            listEmployee.Add(new Employee(4, "abc22"));
            listEmployee.Add(new Employee(5, "abc33"));
        }
        public bool MoveNext()
        {
            bool _retun = false;
            ++position;
            if (position < listEmployee.Count)
                _retun = true;
            return _retun;
        }
        public object Current
        {
            get {
                return listEmployee[position];
            }
        }
        public void Reset()
        {
            position = -1;
        }
    }
    public class EmployeeList
    {
        public EmployeeList()
        { }
        public IEnumerator GetEnumerator()
        {
            return new EnumerateEmployee();
        }
    }

No comments:

Post a Comment