Events and the observer pattern

Events and the Observer pattern

Do you think about learning events not only in Spring Boot? Have you ever thought about what events and observer pattern have in common? Independently, if you say yes or no – that’s great. This article helps you learn or recall the answers to these and more questions :). In the meantime, if you are interested in design patterns, you can find more handy information about design pattern: Adapter .  Additionally, if you would like to read the article in Polish, it is here: Event-y a wzorzec obserwator.

1. The Observer pattern

It is one of the behavioural design patterns in which an object can observe the state of another object and react as business logic wants.  Changes of state are our events. In other words, the Observer pattern is a widespread, simple-to-use messaging method where the subject knows the observers.
Observer-General overviewObserver pattern – general overview. Resource:
The publisher maintains a list of subscribers and knows in which object (magazine, YT channel) they are interested. Subscribers can leave the list at any time when they wish to stop the publisher from sending notifications about the chosen object to them. In our case study observer knows subscribers: Karol and Iwona. Karol is interested in „Classic Rock Music”, and Iwona is interested in Joga with Kasandra YT channel. Therefore, a new joga video notification receive only Iwona. Karol will receive notification only for classic rock music. Moreover, observers can start and stop subscribe channel at anytime they want. To visualize it in Java, please see below how the communication can work.

Observer pattern – java example. Resource: Devword’s chart

2.When to use the Observer pattern?

The observer pattern should be used to carry out data exchange between components of a single application. Moreover, it is perfect to use it for synchronous communications. Secondly, the observer pattern can be used in the back-end and front-end part of the application as an event listener.

3. Sum-up

The Observer is in alignment with the Open/Closed Principle. It allows add a new subscriber classes without changing the publisher code. It works because all subscribers implement the same interface, and the publisher communicates with them only via that interface (and vice versa if there’s a publisher interface). Next, we can establish relations between objects at runtime. However,  we need to remember that observer works synchronous. Additionally, speaking of Spring Boot events – they are built based on the observer pattern. However Spring allows events work asynchronously. On the other hand, observable/publisher have any guarantee that any subscriber is listening him.

Leave a Comment

Twój adres e-mail nie zostanie opublikowany. Wymagane pola są oznaczone *