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.
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).
Written By : Gayashan Bombuwala, Trainee Software Engineer, 99X Technology