Simplifying the Journey, One Step at a Time
In essence, the Iterator Design Pattern transforms your exploration of data structures into a guided journey, revealing one element at a time, empowering you to navigate efficiently and focus on what matters most.
hasNext()
to check for remaining elements and next() to retrieve the next element.hasNext()
to check if there are more elements and next() to retrieve and process each element one at a time.next()
call.class NumberCollection:
def __init__(self):
self._numbers = [1, 2, 3, 4, 5]
def __iter__(self):
return NumberIterator(self._numbers)
class NumberIterator:
def __init__(self, numbers):
self._numbers = numbers
self._index = 0
def __iter__(self):
return self
def __next__(self):
if self._index < len(self._numbers):
number = self._numbers[self._index]
self._index += 1
return number
else:
raise StopIteration
# Client code using the iterator
collection = NumberCollection()
for number in collection:
print(number) # Outputs: 1, 2, 3, 4, 5