- Python Design Patterns - Home
- Python Design Patterns - Introduction
- Python Design Patterns - Gist
- Model View Controller Pattern
- Python Design Patterns - Singleton
- Python Design Patterns - Factory
- Python Design Patterns - Builder
- Python Design Patterns - Prototype
- Python Design Patterns - Facade
- Python Design Patterns - Command
- Python Design Patterns - Adapter
- Python Design Patterns - Decorator
- Python Design Patterns - Proxy
- Chain of Responsibility Pattern
- Python Design Patterns - Observer
- Python Design Patterns - State
- Python Design Patterns - Strategy
- Python Design Patterns - Template
- Python Design Patterns - Flyweight
- Python Design Patterns - Abstract Factory
- Python Design Patterns - Object Oriented
- Object Oriented Concepts Implementation
- Python Design Patterns - Iterator
- Python Design Patterns - Dictionaries
- Python Design Patterns - Lists Data Structure
- Python Design Patterns - Sets
- Python Design Patterns - Queues
- Python Design Patterns - Strings & Serialization
- Python Design Patterns - Concurrency
- Python Design Patterns - Anti Pattern
- Python Design Patterns - Exception Handling
Python Design Patterns Resources
Python Design Patterns - Iterator Pattern
The iterator design pattern falls under the behavioral design patterns category. Developers come across the iterator pattern in almost every programming language. This pattern is used in such a way that it helps to access the elements of a collection (class) in sequential manner without understanding the underlying layer design.
Example - How to implement the iterator pattern?
We will now see how to implement the iterator pattern.
main.py
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 generates the following output −
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 Calculation stopped
If you focus on the pattern, Fibonacci series is printed with the iterator pattern. On forceful termination of user, the following output is printed −
Explanation
This python code follows the iterator pattern. Here, the increment operators are used to start the count. The count ends on forceful termination by the user.
Advertisements