Saturday, September 2, 2023

Iterator Design Pattern in Python...

Iterator design pattern is a behavioral design pattern that lets you access the element of a complex data structure - a collection class - without the knowledge of the internal structure of the elements it is accessing.

To create an iterator in Python, there are two abstract classes from the built-in `collections` module - Iterable, and Iterator. We need to implement the

`__iter__()` method in the iterated object (collection), and the `__next__ ()` method in the iterator.

The concrete class that implements the Iterator class provides various means of different ways of iteration through the collection class.

In our example, AlphabeticalOrderIterator is such a class that has provided forward and reverse ways of iteration. In this example, the WordsCollection class represents a collection of words and implements the Iterable interface.

The source code is as follows:

from collections.abc import Iterator, Iterable
from typing import Any, List

class WordsCollection(Iterable):
def __init__(self, collection: List[Any]=[]):
self._collection = collection

def __iter__(self):
return AlphabeticalOrderIterator(self._collection)

def get_reverse_iterator(self):
return AlphabeticalOrderIterator(self._collection, True)

def add_item(self, item:Any):
self._collection.append(item)

class AlphabeticalOrderIterator(Iterator):
_position = None
_reverse = False

def __init__(self, collection : WordsCollection, reverse: bool = False):
self._collection = collection
self._reverse = reverse
self._position = -1 if self._reverse else 0

def __next__(self):
try:
value = self._collection[self._position]
self._position += -1 if self._reverse else 1
except IndexError:
raise StopIteration()

return value


# Press the green button in the gutter to run the script.
if __name__ == '__main__':
wordsCollection = WordsCollection()
wordsCollection.add_item("Som")
wordsCollection.add_item("Reema")
wordsCollection.add_item("Ridit")

print("Forward traversal:")
print("\n".join(wordsCollection))
print("")

print("Reverse traversal:")
print("\n".join(wordsCollection.get_reverse_iterator()), end="")

If we run the above program the output will be as follows:

Forward traversal:

Som

Reema

Ridit


Reverse traversal:

Ridit

Reema

Som

 

No comments: