This project demonstrates the Observer Pattern using a weather station scenario. The Observer Pattern allows an object (the Subject) to maintain a list of dependents (Observers) and notify them of any state changes, promoting a decoupled design.
Observer-Pattern/
├── __init__.py
├── client.py # Entry point for the application
├── README.md
├── legacy/
│ ├── __init__.py
│ └── weather-station.py # Non pattern implementation
└── observer/
├── __init__.py
├── interface.py
├── observers.py
├── subject.py
└── __pycache__/
- Implements the Observer Pattern to demonstrate decoupled design.
- Includes a weather station example to showcase real-world usage.
- Provides a legacy implementation for comparison.
- The
Subjectmaintains a list of observers and notifies them of state changes. - Observers implement an interface to define their update behavior.
- The
client.pyfile demonstrates the interaction between the subject and observers.
-
Clone the repository.
-
Navigate to the
Observer-Patterndirectory. -
Run the
client.pyfile to see the Observer Pattern in action:python client.py
When you run the client.py file, you will see output similar to the following:
Temperature: 25°C
Humidity: 60%
Pressure: 1013 hPa
- Create a new class that implements the
Observerinterface. - Define the
updatemethod to handle state changes. - Register the new observer with the subject using the
add_observermethod.
- Python 3.7+
- Encapsulation: The subject encapsulates the logic for managing observers.
- Open/Closed Principle: New observers can be added without modifying existing code.
- Loose Coupling: Observers and subjects are loosely coupled, promoting flexibility.