Observer - C++ Patterns
← Patterns

Observer

This pattern is licensed under the CC0 Public Domain Dedication.

Requires c++11 or newer.

Intent

Notify generic observer objects when an event occurs.

Description

The observer pattern allows generic observer objects to be registered with a subject object and receive notifications when certain events occur.

The subject class, defined on lines 17–34, contains a std::vector of references to observers line 33. Observers (also known as listeners), in this case, are objects that implement the observer interface (lines 4–8). The register_observer function (lines 20–23) adds observers to this std::vector, which are later to be notified by the notify_observers function (lines 25–30).

We use std::reference_wrapper for the elements of the std::vector (line 33), because the standard containers require the element type to be assignable, which normal reference types are not.

Contributors

  • Joseph Mansfield
  • Robbie Shade

Last Updated

09 December 2017

Source

Fork this pattern on GitHub

Share

Feel like contributing? This website is generated from a git repository. If you have something to add or have noticed a mistake, please fork the project on GitHub.

C++ Patterns created by Joseph Mansfield