Explore the Observer Design Pattern with C++

Gayashan Bombuwala
2 min readJul 25, 2017

--

Let’s look at how the popular Observer Design Pattern (Publish/Subscribe) can be implemented in C++ in the simplest way. Here, I’m using a weather station example to explain the Observer pattern where when the temperature, humidity and the pressure of the weather station changes, all of its clients will get notified immediately.

Weather Station Example

First let’s look at the definition of the 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.

Why the Observer Pattern is important?

Think about the weather station example. It can have a set of clients (i.e. web apps, mobile apps). Each client should know whenever there is a change in the state of the weather station, otherwise the clients won’t be able to show real time accurate results. The Observer pattern is the solution for these kinds of situations. In this scenario the weather station can be taken as the Publisher (Subject) and each client can be taken as a Subscriber (Observer).

Design (Class Diagram)

Class Diagram

**See how interfaces have been used to leverage a loosely coupled design.

The important thing here is that the WeatherStation class does not need to know about the Client. All it knows is that the Observer implements the Observer interface and vice versa.

Now let’s implement this in C++

I’ll walk you through the implementation step by step you can checkout the full source code using the following GitHub link.

View Full Source Code on GitHub

Subject.hpp
Observer.hpp
WeatherData.hpp
WeatherData.cpp
Client.hpp
Client.cpp

Yeah! It’s done, let’s go for a test drive….

An overview of what’s gonna happen

Here is the main class which you need to run for the test drive.

main.cpp

The Output

Console Output

See you with another tutorial.

Please comment below if you have any issues.

Good Bye

--

--