The Observer Pattern In Go

A fundamental design pattern every software engineer needs to know.

The Observer design pattern is a fundamental tool for any capable software

engineer. In one sentence, it consists of observers that pay close attention to subjects that change their state. In this tutorial, we will explore the use cases, UML diagram and implementation in my current favorite programming language — Go.

Note: The terminology can vary as an observer/subscriber or as a subject/topic/publisher. They are all the same, but I will be using observer and subjects in this article.

Use Cases

The real world examples of the observer design pattern are endless. They include:

  • Social media platforms — friends can follow other friends to share updates with each other. Medium itself could use this pattern!
  • News platforms — people subscribe to news stations (Washington Post for example) and are notified daily/weekly also with breaking news events.
  • Robotic Operating System (ROS) — not an actual operating system, but ROS actually has basic communication with its robots built off of the observer pattern with publishers and subscribers to transfer information.

And so many more!

UML Diagram

Thankfully we have a simple diagram to analyze. You can get variations where the Subject is not an interface, but I think keeping both the Subject and the Observer as interfaces greatly improves the flexibility of your code and provide contracts to scale from.

From yours truly

Starting from top left, the Subject is normally listed as an abstract class, but Go doesn’t have classes so we instead label it as an interface. The ConcreteSubject will implement this interface with this same process applying to Observers.

We have Attach() and Detach() methods in the Subject that both take in an Observer object. There is a composite relationship between Subject and Observer, meaning that we can have a Subject with zero to many Observers. Furthermore both the ConcreteSubject and ConcreteObserver implement the two interfaces with dashed lines, rather than inherit from a class which would be filled in lines (because this is Go after all).

Finally the concrete objects have private states assigned to them which can then be accessed and altered by the public methods in order to maintain integrity.

Note: Go doesn’t have public or private keywords. Instead, public methods start with a capital letter and private methods start with a lowercase letter.

Implementation in Go

In this example we are going to create a program that has sensors to detect changes in temperature with weather stations to broadcast information. The sensors will act as an implementation of the Subject interface, while the stations will be observers of the weather sensors.

Let’s make basic structure that will consist of 3 files.

The Observer Pattern In Go

The Observer Pattern In Go