Design patterns – Observer

observer

The observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods.

Observer pattern is:
– supposedly the most relatable pattern around.
– mainly used to implement distributed event handling systems.
– a key part in the familiar model–view–controller (MVC) architectural pattern.
– implemented in numerous programming libraries and systems, including almost all GUI toolkits.

Indent:
Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

Drawbacks:
– Cascade update may be ‘heavy’ in terms of time and CPU resources.
– Harmless at the first glance, the operation of the subject can cause a number of updated observers and their dependent objects.

Please take into account that the current implementation is not thread-safe!
For that, we would need to add a mutex into all of the functions.
I skipped that because I wanted to present only the design pattern, and not other functionalities.


As for a real life example:
– if you mark to receive updates from a facebook group, you will receive a notification each time someone posts something in it.


Now let’s see some code!

The github code also contains the interfaces with the required functions, here I’ll present the required classes / functions only.

  • We have the following classes:
    • IListener interface, with a virtual function – so we can have different subclasses that can register to the same notification
    • Subclasses that inherit the IListener interface and overwrite the onUpdate function

  • Observer class should contain:
    • A list of listeners
    • A function to register / unregister to an event
    • The event function that will call the onUpdate function on all the registered listeners


The full code can be found at the following link:
https://github.com/badearobert/cplusplus

Leave a comment

Your email address will not be published.