Member-only story
Understanding the Observer Design Pattern
Notifications between objects without polling or busy waiting
There are 23 classic design patterns described in the original book Design Patterns: Elements of Reusable Object-Oriented Software. These patterns provide solutions to particular problems often repeated in software development.
In this article, I am going to describe how the Observer pattern works and when it should be applied.
Observer: Basic Idea
Wikipedia provides us with the following definition:
“The observer pattern is a software design pattern in which an object, named the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods.” — Wikipedia
On the other hand, the definition provided by the original book goes as follows:
“Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.”
On many occasions, we need to communicate with system objects without coupling them either at the code or communication mechanism level. Should we have a group of objects (observers) that are required to be aware of the state of another object (observable), there are different techniques for carrying out the communication between them. The most popular techniques are:
- Busy waiting — A process repeatedly verifies a condition. In our case, it would be an observer constantly checking whether or not the observable’s condition has changed. This strategy could be a valid solution in certain cases, but it isn’t an adequate solution for our scenario since it would imply having several processes (observers) consuming resources without performing any operations, causing an exponential performance decrease in the number of existing observers.
- Polling — In this case, the query operation is performed with a small window of time between operations. This is an attempt to implement synchronism between processes. However, we can once again appreciate degradation in…