[Design Pattern] Observer Pattern

edindevto

Ed is Taking Note

Posted on August 8, 2022

[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

The notify() method will be like:


public void notify() {

    this.status = // Do what ever to get the latest status...;

    this.subscribers.stream().foreach((s) => {
        s.update(this.status);
    });
}

Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
edindevto
Ed is Taking Note

Posted on August 8, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related