OOPs4Humans

Observer Pattern

Don't call us, we'll call you.

Observer Pattern

Analogy: pattern

The Observer Pattern is like a News Station.

Subscribers (TVs, Phones) sign up to receive updates.

When breaking news happens, the Station Broadcasts it to everyone at once. You don't have to keep checking the station ("Is there news? Is there news?").

The News Station

  1. Add Subscribers (Phone, TV, Email).
  2. Type a message and Broadcast.
  3. Watch everyone get updated instantly!

News Station (Observer Pattern)

Publisher

Add Subscribers:

Subscribers List (0)

No subscribers yet.

The Code

The Subject (Station) keeps a list of Observers (Subscribers).

Java Example
Switch language in Navbar
class NewsStation {
    private List<Observer> subscribers = new ArrayList<>();

    public void addSubscriber(Observer sub) {
        subscribers.add(sub);
    }

    public void broadcast(String news) {
        for (Observer sub : subscribers) {
            sub.update(news);
        }
    }
}