Design Pattern Download: The Observer Pattern

Matthew MacFarquhar
2 min readApr 20, 2022

--

The Observer pattern is a Behavioral Pattern used in software engineering when we want to subscribe some objects to another class to enable a push notification system where the Observer class can choose what they want to listen to.

Example

Imagine we have a store which currently has a message board on their website which posts messages about their status. Currently, it is a pain point for a customer to get the status of the store since they will have to continuously check the website to see if anything has changed. Now, the store decides to get the emails of everyone who has ever been a customer (by hacking their Facebook data or something 🙄) and sends an email out to everyone when their status has changed! Problem Solved! Except… 3 days later you receive lots of angry emails from customers complaining that you keep spamming them with your stupid updates about “2-for-1 cans of ham”. So how do we solve this? We allow the customer to let us know IF they want to get our mass market emails and allow them to subscribe and unsubscribe at will.

When to use an Observer?

  • When a subset of class instances need updates on some other object’s status.

What is the Observer composed of?

  • The Observer (the customer)
  • The Object of observation (the store)

Implementation

The Observer

The Object of observation

Now we can send our coupons to the people who really want them and avoid the death threats from pissed of customers and their bloated email inboxes.

Bob has received message HI ALL!
Bill has received message HI ALL!
Bob has received message GOOD MORNING!

--

--

Matthew MacFarquhar
Matthew MacFarquhar

Written by Matthew MacFarquhar

I am a software engineer working for Amazon living in SF/NYC.

No responses yet