Everything you just saw in this article is only a small part of the book Introduction to design patterns, the most complete book of design patterns in Spanish, we cover 25 design patterns along with 25 real-world projects. Forget about learning design patterns with typical Internet examples of how to make pizza, animals, and geometric shapes. I invite you to see my book:
See bookObserver
Behavioral patternThis design pattern allows us to observe the changes suffered by an object, that is, if the observed object suffers any change, a notification will be sent to the observers; this is known as publish-subscribe. Observer is one of the main design patterns used in the development of graphical user interfaces (GUI), because it allows us to decouple the graphical component from the action to be performed.
The components included in the pattern are:
- IObservable: Interface which must be implemented by all objects subject to observation, in it, all the basic implementable methods are defined.
- ConcreteObservable: This is the observable class; it implements IObservable along with its methods.
- IObserver: Interface which must be implemented by all objects in charge of observing the changes on IObservable.
- ConcreteObserver: Concrete class in charge of watching the changes on IObservable, it inherits from IObserver and must implement its methods.
- ObserverA registers into the Observable object in order to be notified of any changes.
- ObserverB registers into the Observable object in order to be notified of any changes.
- The status of the Observablechanges.
- All the Observers are notified that a change has occurred.
Real-world example
By implementing the Observer design pattern, we are going to develop an application that loads the system configuration at the start. This configuration will automatically notify all the observer objects of any changes that would happen in order to let the user know about them. The purpose of this approach is to keep the objects from having to constantly check for changes.