Mastering Design Patterns with Examples — Observer Pattern

Keeping your objects in the know

Larry | Peng Yang
Computer Science Fundamentals

--

Photo by Daniel Lerman on Unsplash

Overview

In the first post of this design pattern series, we introduced three design principles and a design pattern (strategy pattern). In this post, we will learn the fourth design principle and another behavior design pattern — Observer Pattern.

The Observer Pattern defines a one-to-many dependency between objects so that when one object changes state, all of its dependents are notified and updated automatically, here are the key ideas.

  • Keeping the objects in the know
  • Notify objects about something they care about
  • Objects can decide if they want to be informed
  • One of the most heavily used patterns in JDK
  • Loosely coupled many-to-one relationship

Use observer pattern in Weather-O-Rama problem

Let’s take a look at the Weather Monitoring application in the Head First Design Pattern book.

Understand the requirement

The system has three components: the weather station (the physical device that acquires the actual weather data), the WeatherData object (that tracks…

--

--