Implementing the Observer Pattern
In this lesson, we will explain the implementation of the Observer pattern in the C language.
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.
typedef void(*ChangeTimeNotification)(void* instance,const SystemTime* newTime);typedef struct{void* instance;ChangeTimeNotification notification;} TimeObserver;
- 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. ...