Java Design Patterns: Observer

Photo by Artur Rutkowski on Unsplash

In all these years of being a java developer, I’ve seen quite a few design patterns, but the observer isn’t one of them that I’ve seen used very often. Probably because its structure is not fully hierarchical and it can be more difficult to debug and read when you don’t know the code. I also think it’s an interesting design pattern and let’s see it with the following example!

Suppose you have to do a chained action when something happens, a solution would basically be to execute each action sequentially.

UserService userService = new UserService();
ShoppingCartService shoppingCartService = new ShoppingCartService();
// ... more instances here
userService.theMethodThatINeed("coolParam");
shoppingCartService.doingAmazingThings("yes!");
// ... more method calling here

There is nothing really bad regarding this approach in this exact scenario but if you imagine that instead of 2 instances you could have 20, reading it becomes more and more complex… and we don’t want complex code to read, right?

HERE COMES OBSERVER!

We know that these classes need to do something when something happens and we need to do it in all of them. The solution? Why not implement an interface that requires all of them?🤔 Then we will have the OBSERVERS 👀

public interface EventObserver {
void update(Object object);
}

Cool, now we just need to implement it then we can identify who is the observer.

UserService.java

public class UserService implements EventObserver {

@Override
public void update(Object object) {
System.out.println("Something happened, UserService to the rescue!!");
}
}

ShoppingCartService.java

public class ShoppingCartService implements EventObserver {

@Override
public void update(Object object) {
System.out.println("Something happened, ShoppingCartService needs to do something!!");
}
}

Great! We have the observers, but how do they know what are they observing and who is telling them when they need to do these actions? That’s why we need to create a manager that handles all of that for us.

ObserverManager.java

public class ObserverManager {
final List<EventObserver> observers;

public ObserverManager() {
this.observers = new ArrayList<>();
}

public ObserverManager(final EventObserver... observers) {
this.observers = List.of(observers);
}

public void add(final EventObserver eventObserver) {
observers.add(eventObserver);
}

public void remove(final EventObserver eventObserver) {
observers.remove(eventObserver);
}

public void updateAll(final Object object) {
for (EventObserver observer : observers) {
observer.update(object);
}
}

}

Nice! But now how do I do to work with my observers and manager? Super simple!

We have to tell the manager who controls.

Option 1:

ObserverManager observerManager = new ObserverManager(new UserService(), new ShoppingCartService());

Option 2:

ObserverManager observerManager = new ObserverManager();
observerManager.add(new UserService());
observerManager.add(new ShoppingCartService());

And then is something as simple as to notify our observer that something happened and they need to do something.

observerManager.updateAll("Alarm!");

Full example code:

ObserverManager observerManager = new ObserverManager();
observerManager.add(new UserService());
observerManager.add(new ShoppingCartService());
observerManager.updateAll("Alarm!");

Result:

Alarm! Something happened, UserService to the rescue!!
Alarm! Something happened, ShoppingCartService needs to do something!!

This is just a small example, the reason you need this pattern to warn that something happens will depend on your way as a programmer using this design pattern or not.

👇 Did you like the article? Buy me a coffee! 👇

👉 https://www.buymeacoffee.com/rrbapps 👈

--

--

--

Software, travel and adventure

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

What happens with ls *c?

My Internship Journey at LetsGrowMore

#JustStartYourGoals

API Integration | SMS API | Bulk SMS API

Building a personal homepage in 2 days for beginners (1)

asobuがGlobal Game Jam 2022を開催!/ asobu is hosting Global Game Jam 2022

Nexus OSS | Solving the problem of cleaning up the Docker repository

Rust The Most Loved Programming Language

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ricardo Romero Benitez

Ricardo Romero Benitez

Software, travel and adventure

More from Medium

Design Patterns: Singleton

Learning to write unit tests for a real world application

Some of the Java best practices and code conventions.

Abstraction in Object-Oriented Programming- Explained using Java