The Observer Pattern is a behavioral pattern from the book “Design Patterns: Elements of Reusable Object-Oriented Software”. It defines 1-to-n dependencies between objects so that changes to one object cause all dependent objects to be notified.
The Observer Pattern solves a classical design issue: How can you ensure that all prospects are automatically notified if an important event has taken place?
The Observer Pattern
- Defines 1-to-n dependencies between objects so that changes to one object cause all dependent objects to be notified.
Also known as
- Publisher-Subscriber (short Pub/Sub)
- One abstraction depends on the state of another abstraction
- A change to one object implies a change to another object
- Objects should be notified of state changes of another object without being tightly coupled
- Manages its collection of observers
- Allows the observers to register and unregister themself
Defines an interface to notify the observers
- Implements the interface
- Is notified by the
The following program
observer.cpp directly implements the previous class diagram.
Observer supports the member function
notify, and the
Subject supports the member functions
notifyObservers. The concrete observers receive the subject in their constructor and use them to register themself for the notification. They have a reference to the subject (lines 3 and 4). Only
observerA is unregistered in line (1). The member function
notifyObservers goes through all registered observers and notifies them (line 2).
The following screenshot shows the output of the program:
By the way, you may have noticed that I used no memory allocation in the previous program
observer.cpp. This is how virtuality is typically used if you aren’t allowed to allocate memory, such as in deeply embedded systems. Here is the corresponding main function using memory allocation:
- Model-View-Controller: The model represents the data and its logic. The model notifies its dependent component, such as the views. The views are responsible for representing the data, and the controller is for the user input.
- Reactor: The Reactor registers the event handlers. The synchronous event demultiplexer (
select) notifies the handles if an event occurs.
I will dedicate an entire future post to both architectural patterns.
Subject in the program
observer.cpp simply sends a notification. However, more advanced workflows are often implemented:
Subject sends a
- notification that a value is available. Afterward, the Observer has to pick it up.
- notification, including an indication of which value is available. The Observer picks it up if necessary.
- The Mediator Pattern establishes communication between the sender and the receiver. Each communication between the two endpoints goes, therefore, through the mediator. The Mediator and the Observer are pretty similar. The goal of the mediator is to decouple the sender and the receiver. On the contrary, the Observer established a one-way communication between the publisher and the subscriber.
Pros and Cons
- New observers (subscribes) can easily be added to the publisher
- Observers can register and unregister themself at run time
- Neither does the publisher provides a guarantee in which order the subscribers are notified, nor does it gives the assertion of how long the notification takes when you have many subscribers.
- The publisher may send a notification, but a subscriber is not alive anymore. To avoid this drawback, you can implement the destructor of the concrete observers in such a way that the concrete observers unregister themself in its destructor:
The concrete observer
ConcreteObserverA models the RAII Idiom: It registers itself in its constructor and unregisters itself in its destructor.
The Visitor Pattern has an ambivalent reputation. On one hand, enables the Visitor Double Dispatch. On the other hand, the Visitor is pretty complicated to implement. Let me introduce the Visitor Pattern in my next post.
Thanks a lot to my Patreon Supporters: Matt Braun, Roman Postanciuc, Tobias Zindl, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Jozo Leko, John Breland, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Kris Kafka, Mario Luoni, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Daniel Hufschläger, Alessandro Pezzato, Bob Perry, Satish Vangipuram, Andi Ireland, Richard Ohnemus, Michael Dunsky, Leo Goodstadt, John Wiederhirn, Yacob Cohen-Arazi, Florian Tischler, Robin Furness, Michael Young, Holger Detering, Bernd Mühlhaus, Matthieu Bolt, Stephen Kelley, Kyle Dean, Tusar Palauri, Dmitry Farberov, Juan Dent, George Liao, Daniel Ceperley, Jon T Hess, Stephen Totten, Wolfgang Fütterer, Matthias Grün, Phillip Diekmann, Ben Atakora, Ann Shatoff, Rob North, Bhavith C Achar, and Marco Parri Empoli.
Thanks, in particular, to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, John Nebel, Mipko, Alicja Kaminska, Slavko Radman, and David Poole.
|My special thanks to Embarcadero|
|My special thanks to PVS-Studio|
|My special thanks to Tipi.build|
|My special thanks to Take Up Code|
I’m happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.
- Embedded Programmierung mit modernem C++ 12.12.2023 – 14.12.2023 (Präsenzschulung, Termingarantie)
Standard Seminars (English/German)
Here is a compilation of my standard seminars. These seminars are only meant to give you a first orientation.
- C++ – The Core Language
- C++ – The Standard Library
- C++ – Compact
- C++11 and C++14
- Concurrency with Modern C++
- Design Pattern and Architectural Pattern with C++
- Embedded Programming with Modern C++
- Generic Programming (Templates) with C++
- Clean Code with Modern C++
- Phone: +49 7472 917441
- Mobil:: +49 176 5506 5086
- Mail: schulung@ModernesCpp.de
- German Seminar Page: www.ModernesCpp.de
- Mentoring Page: www.ModernesCpp.org
Modernes C++ Mentoring,