Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do we still need Iterator design pattern? [closed]

I am learning the design patterns, and I found Iterator. Do we still need to use it?

Since we have collection, I am confused why we still need the Iterator Design Pattern.

like image 568
kevin Avatar asked Feb 28 '11 09:02

kevin


People also ask

Why do we need Iterator pattern?

Iterator pattern is useful when you want to provide a standard way to iterate over a collection and hide the implementation logic from client program. The logic for iteration is embedded in the collection itself and it helps client program to iterate over them easily.

What is the benefit of using an iterator design pattern?

Iterator Pattern: AdvantagesThe code is easier to use, understand and test since the iterator uses the Single Responsibility and Open/Closed SOLID principles. The Single Responsibility Principle allows us to clean up the client and collections of the traversal algorithms.

What problem does the iterator design pattern solve?

The Iterator design pattern allows us to separate out all the logic for iterating over a collection. There are different collection objects and all of them need their own iterator. The reason is each collection has its own structure.

What is the main idea behind the iterator design pattern?

The main idea of the Iterator pattern is to extract the traversal behavior of a collection into a separate object called an iterator. Iterators implement various traversal algorithms. Several iterator objects can traverse the same collection at the same time.


1 Answers

IEnumerator<T> is an iterator and IEnumerable<T> creates them. Almost all collections implement IEnumerable<T>.

It's at the heart of Linq-To-Objects which is one of the core features of C# 3. So iterators are very important in modern C#.

C# 3 also introduced a special language feature allowing you to easily implement an iterator using the yield return syntax.

foreach is based on iterators too.

like image 149
CodesInChaos Avatar answered Sep 21 '22 17:09

CodesInChaos