DEV Community

Ed is Taking Note
Ed is Taking Note

Posted on

1 1

[Design Pattern] Observer Pattern

The observer pattern is a one to many relationship dependency, and when one object(Observable object) changes its status, all its dependencies(Observer objects) will be notified and updated accordingly.

Scenario Problem
Now we have a publisher object and many subscriber objects, and subscriber objects poll new status from the publisher. However, all these subscribers don't know when the publisher will update a new status, so they just keep polling new status from the publisher(like polling every 1 minute or something).

problem

Now there comes a bad smell... What if there are like 1000 subscribers and each of them tries to get status every 10 seconds!?
As a result, the requesting traffic must explode and obviously there are lots of unnecessary calling... Also, subscribers might not get the most recent status - there is still up to 10 seconds delay before getting the status.

Solution
With the observable pattern, every time the publisher(Observable object) has a new status, it notifies all its subscribers. This way we can avoid lots of unnecessary callings, and all subscribers can get the most recent status immediately without delay.

solution

Implementation
A very simple class diagram of the pattern is like the following:

Implementation

We have register() and unregister() methods to add or remove subscriber to the subscribers list of the publisher class.

The publisher's notify() method will be like:

public void notify() {

    this.status = // Do whatever to get the latest status...;

    this.subscribers.stream().foreach((s) -> {
        s.update(this.status);
    });
}
Enter fullscreen mode Exit fullscreen mode

The subscriber's update() method will be like:

public void update(Object status) {
     // Do whatever the subscriber want to do with the received status.
}

Enter fullscreen mode Exit fullscreen mode

This is a very basic and simple observer pattern. There are actually many different kinds of implementation for observer pattern, but the core concept is generally the same.

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay