Python Design Patterns Tutorial
Python Design Patterns Resources
Selected Reading
- Exception Handling
- Python Design Patterns - Anti
- Concurrency in Python
- Strings & Serialization
- Python Design Patterns - Queues
- Python Design Patterns - Sets
- Lists Data Structure
- Dictionaries
- Python Design Patterns - Iterator
- Object Oriented Concepts Implementation
- Object Oriented
- Abstract Factory
- Python Design Patterns - Flyweight
- Python Design Patterns - Template
- Python Design Patterns - Strategy
- Python Design Patterns - State
- Python Design Patterns - Observer
- Chain of Responsibility Pattern
- Python Design Patterns - Proxy
- Python Design Patterns - Decorator
- Python Design Patterns - Adapter
- Python Design Patterns - Command
- Python Design Patterns - Facade
- Python Design Patterns - Prototype
- Python Design Patterns - Builder
- Python Design Patterns - Factory
- Python Design Patterns - Singleton
- Model View Controller Pattern
- Python Design Patterns - Gist
- Introduction
- Python Design Patterns - Home
Python Design Patterns Resources
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Python Design Patterns - Observer
Python Design Patterns - Observer
In this pattern, objects are represented as observers that wait for an event to trigger. An observer attaches to the subject once the specified event occurs. As the event occurs, the subject tells the observers that it has occurred.
The following UML diagram represents the observer pattern −
How to implement the observer pattern?
Let us now see how to implement the observer pattern.
import threading import time import pdb class Downloader(threading.Thread): def run(self): print downloading for i in range(1,5): self.i = i time.sleep(2) print unfunf return hello world class Worker(threading.Thread): def run(self): for i in range(1,5): print worker running: %i (%i) % (i, t.i) time.sleep(1) t.join() print done t = Downloader() t.start() time.sleep(1) t1 = Worker() t1.start() t2 = Worker() t2.start() t3 = Worker() t3.start()
Output
The above program generates the following output −
Explanation
The above code explains the procedure of downloading a particular result. As per the observer pattern logic, every object is treated as observer. It prints the output when event is triggered.
Advertisements