Iterator Method

Iterator Method

Iterator Method

The iterator method is a behavioural design pattern that allows you to transverse elements of a collection without exposing its underlying elements or representations. It also gives a way to access the elements of complex data-structure sequentially without repeating them. Programmers regularly use the iterator method, and it helps to access the elements of a collection (class) consecutively without understanding the underlying layer design.

Implementation

The Fibonacci series would be an excellent example for implementing the iterator method and this is done using python

# Import time library
import time
def fibonaci():
    a, b = 0, 1
    while True:
        yield b
        a, b = b, a + b


if __name__ == "__main__":
    
    g = fibonaci()
    try:
        for e in g:
            print(e)
            time.sleep(1)
    except KeyboardInterrupt:
        print("Calculation stopped")

Code Output: The code above generates the output below-:

ProBook:~/InfosecAddicts/$ python iterator.py
1
1
2
3
5
8
13
21
34
55
89
144
^CCalculation stopped

From the result, the Fibonacci series prints with the iterator method and it is terminated by the user forcefully.

Pros and Cons

Pros
  • Easy Interface
  • Open/Closed Principle
  • Single Responsibility Principle
Cons
  • Increased Complexibility
  • Decrease in Efficiency

 

 

 

 

 

Lesson Content