Porting the Observer Pattern to Python

Porting a simplified version of the Weather Observer program to Python proved to be pretty straight forward, especially since most of the classes and methods were already provided to us ported over. The one issue I initially encountered came when I tried to implement humidity into the display. My first thought was to simply copy the following method:

    def setTemperature(self, temperature):
        self.temperature = temperature
        self.notifyObservers()

and create another version for Humidity:

    def setHumidity(self, humidity):
        self.humidity = humidity
        self.notifyObservers()

I then would call each method in the driver to set a value using:

weatherData.setTemperature(78.0)
weatherData.setHumidity(30.0)

The problem with this was that as soon as the program got through the setTemperature method it would then notify the observers without running through the setHumidity method and the output would initially be 78.0 and None, rather than 78.0 and 30.0.

When I finally tracked down what was happening it occurred to me to make a single setMeasurements method as below:

    def setMeasurements(self, temperature, humidity):
        self.temperature = temperature
        self.humidity = humidity
        self.notifyObservers()
weatherData.setMeasurements(78.0, 30.0)

Once I implemented those changes the appropriate output was produced:

Current Conditions: 78.0F degrees and 30.0% humidity
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s