Design Patterns for Dummies. The Iterator Pattern
In continuation with the series on design pattern, I am currently going through Behavioral Patterns. Today I will write about the Iterator Pattern. You can read about rest of the patterns from the following links
- Strategy Pattern
- State Pattern
- Template Method Pattern
- Chain of Responsibility Pattern
- Command Pattern
You can read about the Structural patterns here.
You can read about the Creational patterns here.
The Iterator patterns deals with providing an easy way to access elements of a collection sequentially. To implement an iterator in C#, we can implement either IEnumerator or the IEnumerable interfaces. IEnumerator interface has 2 methods GetEnumerator and Reset which we would have to implement and an Current object which is used to maintain the position. The easier way of doing it is to implement the IEnumerable interface and implement the GetEnumerator method for it. In the following example I am using the yield return statement in the GetEnumerator method which saves us from maintaining the state.
We can implement our iterator when we want iterations over a collection or we have many ways of traversing it or when there are many collections for traversing.
In my next post I will be writing about the Mediator Pattern.
Comments