Design Patterns — The Observer Pattern

This is part 2 of my design patterns articles.
A lot of credit to Christopher Okhravi. I’m trying to cover all his videos about design patterns from the book “Head First: Design Patterns”.

Let’s think about a weather app.
The app got some weather class, which has a state of the current weather,
and once the weather changes/updates, all the dependent classes which need to “subscribe” to the weather, need to display the new updated weather.

Example to the interfaces:

The observable needs to notify the subscribers on every change of his state.
Therefor, the observable should have:

1- List of all the subscribers
2- Way to add \ remove subscribers
3- Some action to push the alert to every subscriber on state change
4- A public method to get the state

Example to an Observable class:

Example to observers classes:

Now, we want to add all the subscribers to the observable class,
so when the state will change, every class will be notified.

The result:

Each observer update method, was invoked.
That was a quick one. I really think its a simple design, so no need to expand more about it, and I like to keep things short and simple.

Hope you enjoyed!