Observer
Updated: 03 September 2023
The Observer pattern defines a one to many dependency between objects so that when one object changes state, all it’s dependencies are notfied of this change
The Observer pattern is used to enable one object to subscribe to some changes of another object. It allows us to move from a poll
type architecture to a push
type architecture
This pattern allows a client (observer) to subscribe to messages/changes from a subject (an observarble), provided the observable is made aware of all observers
Example
A broad idea of the what an observable and observer would contain may look something like this:
Definition of Classes
An example implementation is seen below:
Usage
Using this kind of framework, we can have other classes that extend the IObserver
and by creating and registering these we can have different classes that all react to the Notify
function calls
In a real implementation you may want to consider using the C# built-in implementation, this makes use of a lot of additional functionality like correct instance disposing, etc. Information on that can be found in the docs
Implementations can differ between different languages/frameworks, you can view implementations in different languages on Refactoring Guru