Python Design Patterns Iterator Pattern

Python Design Patterns: Iterator Pattern

The iterator design pattern falls under the category of behavioral design patterns. Developers encounter the iterator pattern in nearly every programming language. This pattern helps access the elements of a collection (class) sequentially without understanding the underlying design.

How to Implement the Iterator Pattern

We will now see how to implement the iterator pattern.

import time

def fib():
a, b = 0, 1
while True:
yield b
a, b = b, a + b

g = fib()

try:
for e in g:
print(e)
time.sleep(1)

except KeyboardInterrupt:
print("Calculation stopped")

Output

The above program produces the following output –

Python Design Patterns - Iterators

If you pay attention to the pattern, the Fibonacci sequence and iterator pattern are printed. When the user is forcibly terminated, the following output is printed.

Python Design Patterns - Iterators

Explanation

This Python code follows the iterator pattern. Here, the increment operator is used to start counting. The count ends when the user forcibly terminates the program.

Leave a Reply

Your email address will not be published. Required fields are marked *