Kamaropoulos / COVID19Py

A tiny Python package for easy access to up-to-date Coronavirus (COVID-19, SARS-CoV-2) cases data.
https://pypi.org/project/COVID19Py/
GNU General Public License v3.0
84 stars 57 forks source link

Applied Observer Pattern #152

Closed pranishnepal closed 3 years ago

pranishnepal commented 3 years ago

Applied The Observer Pattern

I implemented The Observer Design Pattern to the project's _update() method.

Why is this important?

As of now, the project is quite small and does not offer many extras features. However, If the project were to be extended, the observer pattern makes possible several features. An observer pattern primarily is a "reactor"; when some objects change, other objects monitoring that object can react to the change in some ways.

How

In the original project, previousData would be updated to the old value of latestData everytime new data for latestData was fetched. This is where observer pattern comes into play. Setting latestData as the publisher and previousData as a subscriber, everytime latestData is changed, previousData is updated correspondingly.

To achieve this publisher-subscriber relationship, I created a new class GenericPublisher in publisher.py; this class represents a general class. Second, created another class LatestDataPublisher that extends the GenericPublisher class. LatestDataPublisher holds the latestData. Third, I created a new class PreviousDataSubscriber, which represents the previousData we previously had. Now, i set up the publisher-subscriber relationship in the COVID19 class, creating references to LatestDataPublisher (latestDataPublisher) and PreviousDataSubscriber (previousDataObserver) in the constructor. Finally, whenever _update() is called, to update the what was previously latestData (now latestDataPublisher.latestData), set_latestData() method is called with the value to update it with and notifyObservers() is called to update previousDataObserver.previousData .

Test

To ensure the changes work correctly, I created a test file test_observer_pattern.py. The tests were written using pytest, as such requirements.txt has been updated.

Is there any existing behaviour change due to this modification?

No, everything works the way it was.