Iterator Design Pattern using Python
Iterator design pattern gives a way to access elements of a Collection in a sequential manner. It does not have to know the underlying working for the iteration to work.
Key Components:
from abc import ABC
class IShoppingListIterator(ABC):
def has_next(self):
pass
def next(self):
pass
class IShoppingListCollection(ABC):
def createIterator(self) -> IShoppingListIterator:
pass
class ShoppingListIterator(IShoppingListIterator):
def __init__(self, shopping_list: list[str]) -> None:
self._shopping_list = shopping_list
self._current_index = 0
def has_next(self):
return self._current_index < len(self._shopping_list)
def next(self):
current_item = self._shopping_list[self._current_index]
self._current_index += 1
return current_item
class ShoppingListCollection(IShoppingListCollection):
def __init__(self, shopping_list) -> None:
self._shopping_list = shopping_list
def createIterator(self) -> IShoppingListIterator:
return ShoppingListIterator(self._shopping_list)
def main():
shopping_list = ["eggs", "apples", "butter"]
aggregator = IShoppingListCollection(shopping_list=shopping_list)
iterator = aggregator.createIterator()
while iterator.has_next():
print(iterator.next())
main()
Please find the notebook on Google Colab for a simple implementation of Iterator Design Pattern using #Python.?More implementations will be posted soon!
Happy learning!
#softwaredevelopment #softwaredesignpatterns