Design patterns in C# – part 18 (Iterator pattern)

Role

The Iterator pattern provides a way of accessing elements of a collection sequentially, without knowing how the collection is structured.

Design

IteratorPattern

Implementation

  • Client -> TestIteratorPattern
  • IEnumerable -> IEnumerable
  • Collections -> Days
using System;
using System.Collections;

namespace IteratorPattern
{
    public class TestIteratorPattern
    {
        private const string Splitter = "---------";

        public static void Main(string[] args)
        {
            var days = new Days();

            Console.WriteLine(Splitter);

            foreach (object day in days)
            {
                Console.WriteLine(day);
                Console.WriteLine(Splitter);
            }
        }
    }

    public class Days : IEnumerable
    {
        private readonly string[] _days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};

        #region IEnumerable Members

        public IEnumerator GetEnumerator()
        {
            foreach (string day in this._days)
            {
                yield return day;
            }
        }

        #endregion
    }
}

OUTPUT:

———
Monday
———
Tuesday
———
Wednesday
———
Thursday
———
Friday
———
Saturday
———
Sunday
———

Use when

You are iterating over a collection and one of these conditions holds:

  • There are various ways of traversing it (several enumerators).
  • There are different collections for the same kind of traversing.
  • Different filters and orderings might apply.

Bibliography

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s