Observer Pattern Weather Introduction


This entry is part 1 of 2 in the series Observer Pattern

This post follows chapter two the Observer Pattern of the book called Head First Design Patterns. I will write the code in C# using Visual Studio Community 2019 in a Windows Presentation Foundation project. The code in the book is Java, but the languages are so similar that I was able to write it in C# easily.

In the book it says: “The observer pattern defines a one-to-many dependency between objects so that when one object changes state, all of its dependencies are notified and updated automatically.”

This use-case of the observer pattern is based on a weather station. Weather constantly changes. We track current weather conditions (temperature, humidity, and barometric pressure. Imagine an object that changes state. The data inside is always changing because the sensors at the weather station are reporting changing conditions. Imagine another object that wants to be updated of these changes. It’s our weather object. Does the weather object need to query the station object constantly? Perhaps the weather station should push the data out to our object each time it changes. Should we be pushing or pulling? Observer pattern helps us design a push system, not a pull one. Think of notifications.

Another use-case of the observer pattern is a chat room.

Observable and Observers

An Observable is sometimes called a Subject. The Observable pushes it’s new state data to its Observers. If you Google observer pattern you will find there are flavors of the pattern and different UML diagrams illustrating the different flavors. Regardless of the flavor, our observable object needs to have a list of objects that need to know what has changed. The Subject is going to push the data out to all of the Observers. It will need methods to add to the list, remove from the list, and send out the changes (notify observers). The observers will need an update method.

Below is the screenshot of the Windows Presentation Foundation (WPF) program I wrote that illustrates the Observer Pattern with the example from the book Head First Design Patterns.

Series NavigationWeather Data Code >>