0
0
LldConceptBeginner · 3 min read

Iterator Pattern: Definition, Example, and Usage

The Iterator Pattern is a design pattern that provides a way to access elements of a collection one by one without exposing its underlying structure. It separates the traversal logic from the collection itself, allowing uniform access to different types of collections.
⚙️

How It Works

Imagine you have a box full of different toys, and you want to look at each toy one by one without dumping the whole box out. The Iterator Pattern acts like a helper who hands you each toy in order, hiding how the toys are stored inside the box.

In programming, collections like lists or sets store many items. Instead of letting you peek inside how they keep these items, the iterator gives you a simple way to move through them one at a time. This keeps the collection safe and lets you use the same method to go through different collections.

💻

Example

This example shows a simple iterator for a list of numbers. The iterator lets you get each number one by one without knowing how the list works inside.

python
class NumberIterator:
    def __init__(self, numbers):
        self._numbers = numbers
        self._index = 0

    def has_next(self):
        return self._index < len(self._numbers)

    def next(self):
        if self.has_next():
            number = self._numbers[self._index]
            self._index += 1
            return number
        else:
            raise StopIteration

# Using the iterator
numbers = [10, 20, 30]
iterator = NumberIterator(numbers)
while iterator.has_next():
    print(iterator.next())
Output
10 20 30
🎯

When to Use

Use the Iterator Pattern when you want to go through a collection without exposing its internal structure. It is helpful when you have different types of collections but want to use the same way to access their items.

For example, in a music app, you might have playlists stored differently but want to play songs one by one. An iterator lets you do this smoothly. It also helps when you want to keep your code clean and separate the way you access items from how they are stored.

Key Points

  • The iterator provides a simple way to access elements sequentially.
  • It hides the internal structure of the collection.
  • Supports different collection types with a common interface.
  • Helps keep code clean and separate concerns.

Key Takeaways

The Iterator Pattern lets you access collection items one by one without exposing internal details.
It provides a common way to traverse different types of collections.
Use it to keep traversal logic separate from collection storage.
It simplifies code and improves flexibility when working with collections.