Friday, June 7, 2013

Iterator Design Patterns (Behavioral Patterns) in C#

Iterator: Provides a way to sequentially access aggregate objects without exposing the 
structure of the aggregate.

**Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.

class Program
    {
        static void Main(string[] args)
        {
            ConcreteAggregate a = new ConcreteAggregate();
            a[0] = "Item A";
            a[1] = "Item B";
            a[2] = "Item C";

            ConcreteIterator i = new ConcreteIterator(a);
            Console.WriteLine("Iterating over collection");
            object item = i.First();
            while (item != null)
            {
                Console.WriteLine(item);
                item = i.Next();
            }
            Console.ReadKey();
        }
    }

    abstract class Aggregate
    {
        public abstract Iterator CreateIterator();
    }
    class ConcreteAggregate : Aggregate
    {
        private ArrayList listItems = new ArrayList();
        public override Iterator CreateIterator()
        {
            return new ConcreteIterator(this);
        }
        public int Count
        {
            get { return listItems.Count; }
        }
        public object this[int index]
        {
            get { return listItems[index]; }
            set { listItems.Insert(index, value); }
        }
    }

    abstract class Iterator
    {
        public abstract object Next();
        public abstract object First();
        public abstract bool isDone();
        public abstract object CurrentItem();
    }
    class ConcreteIterator : Iterator
    {
        private ConcreteAggregate _aggregate;
        private int current = 0;
        public ConcreteIterator(ConcreteAggregate aggregate)
        {
            _aggregate = aggregate;
        }
        public override object Next()
        {
            object ret = null;
            if (current < _aggregate.Count - 1)
                ret = _aggregate[++current];
            return ret;
        }

        public override object First()
        {
            return _aggregate[0];
        }

        public override bool isDone()
        {
            return current >= _aggregate.Count;
        }

        public override object CurrentItem()
        {
            return _aggregate[current];
        }
    }

No comments:

Post a Comment