Skip to content

dotnet-simformsolutions/iterator-design-pattern

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Iterator Design Pattern

  • The Iterator Design Pattern allows sequential access to elements without exposing the inside logic. That means using the Iterator Design Pattern, we can access the elements of a collection sequentially without knowing its internal representations.

  • Iterator pattern falls under behavioral pattern category.

Example to Understand Iterator Design Pattern in C#:

  • Suppose we have a collection of employees. Then, we can easily iterate through the collection using either for or for each loop in C#, as shown in the below code.

    image

  • Here, the for-each loop sequentially accesses the elements from the collection without exposing the internal logic, i.e., how it is accessing the elements sequentially. Again, you need to change the client code to use a different data structure. Is it not nice to provide a uniform interface for traversing different collections?

  • For example, your application may have different types of collections, such as List, Array, ArrayList, Generic Dictionary, etc. For whichever type of collection you have, you will need to traverse or iterate through the elements of the collections sequentially. The actual implementation of how to traverse different types of collections will be different, yet the client code should not be concerned about the details of the implementations. The Iterator Design Pattern helps you to hide such details and provides a generic interface for the client to traverse different types of collections, as shown in the image below.

image

Let's implement this above example :

  • Step 1: Create the Collection Item

    image

  • Step 2: Creating Aggregate Interface that has one method CreateIterator.

    image

    image

  • Step 3: Creating Concrete Iterator. This will be a concrete class implementing the Iterator interface and providing implementations for Iterator interface methods.

    image

    image

  • Step 6: Client Code

    image

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •  

Languages