Implementing the Observer Pattern
Explore how to implement the Observer pattern in C, focusing on decoupling subjects from observers using void pointers and function pointers. Understand observer registration, handling of dependencies, and notification models including push and pull, to manage updates efficiently and safely in C programs.
Implementation Mechanism
To decouple the subject from its concrete observers and still enable the subject to notify them,
each observer must correspond to a unique instance. The First-Class ADT pattern provides a way
to realize this. However, as seen from the subject, all observers must be abstracted as one general type
sharing a common interface. In the C language, without language support for inheritance, generality is
usually spelled void*. We can convert any pointer to an object to void* and back to its original type again without losing information. This rule makes a common interface possible.
- The interface above declares a pointer to a function, which proves to be an efficient technique for implementing dynamic behavior
- A concrete observer attaches itself, together with a pointer to a function, at the subject. As the subject changes, it notifies the observer through the attached function.
By using void* as abstraction, we trade type-safety for flexibility. This technique also makes the programmer responsible for converting the observer back to its original type.
A conversion back to another type than the original may have disastrous consequences. Although not very experienced ...