đź“…Week-3 (Day-2) - Understanding the Observer Design Pattern: Real-Life Applications and Code

Payal KumariPayal Kumari
5 min read

NOTE: - I started my 8-week system design journey with Coder Army. I will be journaling every day, recording what I learn, reflecting on it, and sharing it with my network to help newcomers to system design.

đź’  What is the Observer Design Pattern?

The Observer Pattern defines a one-to-many relationship between objects.
➡️ When one object changes its state, all its dependents (observers) are automatically notified and updated.

(Hindi: Observer Pattern ek aisa design pattern hai jisme ek object ke badlav hone par kai aur objects ko turant pata chal jaata hai aur woh update ho jaate hain.)

đź’  Real-World Examples (Observer Pattern in Real Life)

1. YouTube Channel & Subscribers

You subscribe to a YouTube channel.
Whenever the creator uploads a new video, you get a notification.

📍 Here’s the mapping:

  • Channel = Subject (Observable)

  • Subscribers = Observers

When the subject (channel) updates, all registered observers (subscribers) are notified!

(Hindi: Jab aap kisi YouTube channel ko subscribe karte ho, aur naya video aata hai toh aapko notification milta hai. Yehi observer pattern hai!)

📍 Unsubscribe Logic:
👉 If a user unsubscribes, they are removed from the observer list.
So, they won’t receive any further notifications from that channel.

That’s how the Observer Pattern handles dynamic subscriptions!

(Hindi: Agar aap YouTube se unsubscribe karte hain, toh us channel ka koi update ya notification aapko nahi milta. Kyunki ab aap observer list mein nahi ho!)

2. Notification Services (Tech Example)

  • WhatsApp chats

  • Email alerts

  • Instagram DMs

All of them follow Observer Pattern!

Whenever there's new activity, your app (observer) gets instantly notified by the backend service (subject).
But if you disable notifications or mute the chat, your device stops receiving updates — just like removing the observer from the list.

(Hindi: WhatsApp group ko mute karna ya Insta notifications off karna matlab observer pattern mein observer ko hata dena.)

3. Event Listeners in Programming

  • You add a click listener to a button.

  • When the button is clicked, it triggers an event (callback function runs).

button.addEventListener("click", handleClick);  // Subscribe (Observer added)

button.removeEventListener("click", handleClick);  // Unsubscribe (Observer removed)

This is the most relatable example for front-end devs:

The button is being observed, and clicking it triggers a handler. Remove the listener and nothing happens on click!

(Hindi: Yahan button observer pattern ka example hai. Jab tak listener hai, tab tak click hone par kaam hota hai. Listener hata diya, toh kuch nahi hoga.)

đź’  Java Code: YouTube Channel & Subscribers :

interface Observer { 
    void update(String message);
}

class Subscriber implements Observer {
    private String name;

    Subscriber(String name) {
        this.name = name;
    }

    public void update(String message) {
        System.out.println(name + " received: " + message);
    }
}

class YouTubeChannel {
    private List<Observer> subscribers = new ArrayList<>();

    void subscribe(Observer obs) {
        subscribers.add(obs); // Observer added (Subscribe)
    }

    void unsubscribe(Observer obs) {
        subscribers.remove(obs); // Observer removed (Unsubscribe)
    }

    void notifyAll(String message) {
        for (Observer obs : subscribers) {
            obs.update(message); // Notifying all current subscribers
        }
    }
}

"When you subscribe to a channel, you start receiving updates. When you unsubscribe, the updates stop."

You can call subscribe() and unsubscribe() methods to dynamically control notifications.

đź’  Use in Real Projects like YouTube

  • Building your own Notification System

  • Using Webhooks, Realtime Events, or Pub/Sub Architecture

  • Event-driven microservices

Example : "Jab ek user new blog publish karta hai (like on Hashnode), sab followers ko email ya app notification milta hai."

âś… Pros of Observer Pattern

  • Decouples Subject & Observer

  • Real-time updates

  • Scales well for many listeners

❌ Cons (SRP Violation)

  • Subject class becomes heavy (has to manage many observers)

  • Breaking SRP (Single Responsibility Principle) if not separated well

(Hindi: Agar observer logic ko alag class mein na rakha jaye toh main class kaafi complex ho jaata hai.)


import java.util.ArrayList;
import java.util.List;

interface ISubscriber {
    void update();
}

// Observable interface: a YouTube channel interface
interface IChannel {
    void subscribe(ISubscriber subscriber);
    void unsubscribe(ISubscriber subscriber);
    void notifySubscribers();
}

// Concrete Subject: a YouTube channel that observers can subscribe to
class Channel implements IChannel {
    private List<ISubscriber> subscribers;
    private String name;
    private String latestVideo;

    public Channel(String name) {
        this.name = name;
        this.subscribers = new ArrayList<>();
    }

    @Override
    public void subscribe(ISubscriber subscriber) {
        if (!subscribers.contains(subscriber)) {
            subscribers.add(subscriber);
        }
    }

    @Override
    public void unsubscribe(ISubscriber subscriber) {
        subscribers.remove(subscriber);
    }

    @Override
    public void notifySubscribers() {
        for (ISubscriber sub : subscribers) {
            sub.update();
        }
    }

    public void uploadVideo(String title) {
        latestVideo = title;
        System.out.println("\n[" + name + " uploaded \"" + title + "\"]");
        notifySubscribers();
    }

    public String getVideoData() {
        return "\nCheckout our new Video : " + latestVideo + "\n";
    }
}

// Concrete Observer: represents a subscriber to the channel
class Subscriber implements ISubscriber {
    private String name;
    private Channel channel;

    public Subscriber(String name, Channel channel) {
        this.name = name;
        this.channel = channel;
    }

    @Override
    public void update() {
        System.out.println("Hey " + name + "," + channel.getVideoData());
    }
}

public class ObserverDesignPattern {
    public static void main(String[] args) {
        // Create a channel and subscribers
        Channel channel = new Channel("CoderArmy");

        Subscriber subs1 = new Subscriber("Varun", channel);
        Subscriber subs2 = new Subscriber("Tarun", channel);

        // Varun and Tarun subscribe to CoderArmy
        channel.subscribe(subs1);
        channel.subscribe(subs2);

        // Upload a video: both Varun and Tarun are notified
        channel.uploadVideo("Observer Pattern Tutorial");

        // Varun unsubscribes; Tarun remains subscribed
        channel.unsubscribe(subs1);

        // Upload another video: only Tarun is notified
        channel.uploadVideo("Decorator Pattern Tutorial");
    }
}

đź’ Final Thoughts

Observer Pattern is everywhere – from notifications to live updates.
🔄 Whenever you want to automatically inform others when something changes — think Observer Pattern.

👉 Use it wisely, break into modular code, and you’ll be building scalable systems just like YouTube, WhatsApp, and Amazon!

(Hindi: Jab kisi system mein automatic update ka feature chahiye, tab Observer pattern perfect hota hai!)

Week - 3 (Day 2) Completed âś… System Design

NOTE : - A big thanks to my mentors Rohit Negi Sir and Aditya Sir for launching this amazing 8-week course absolutely free on YouTube via CoderArmy9 :- youtube.com/@CoderArmy9 . 🙌

👉 Share this blog with your connections! Let’s keep learning, growing, and supporting one another on this journey. 🚀

✍️ Payal Kumari 👩‍💻 Github

Follow me : X

Jai Hind 🇮🇳 | #CoderArmy #LearningInPublic #SystemDesign #TechForAll #MentorshipMatters #8weeksLLdChallenge #LowLevelDesign #LLD

0
Subscribe to my newsletter

Read articles from Payal Kumari directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Payal Kumari
Payal Kumari

I'm a passionate full-stack developer with a strong foundation in the MERN stack—building and maintaining scalable web applications using React.js, Node.js, and Next.js. My journey in open source began with Hacktoberfest 2023, where I made four impactful pull requests that sparked a love for collaborative coding, global learning, and open knowledge sharing. Since then, I’ve contributed to and mentored projects in top open source programs like GSSoC’24, SSOC’24, and C4GT’24. As a Google Gen AI Exchange Hackathon ’24 Finalist and Google’s Women Techmakers (WTM) Ambassador, I’ve been privileged to support diverse communities in building meaningful tech solutions. My work as a Top 50 Mentor for GSSoC ’24 reflects my commitment to nurturing new talent in tech. Beyond development, I serve as a Student Career Guide, Profile Building Expert & Evangelist at Topmate.io, where I conduct workshops, guide students through resume building and career strategy, and help mentees navigate open source and tech careers. Recognized among the Top 5% of mentors and featured on “Topmate Discover,” I take pride in making mentorship accessible and impactful. My technical voice has also been acknowledged by LinkedIn, where I’ve earned the Top Voice badge seven times in domains like web development, programming, and software engineering. In addition, I hold LinkedIn Golden Badges for Research Skills, Interpersonal Skills, Critical Thinking, and Teamwork—signaling a well-rounded approach to both individual contribution and team collaboration. Graduating with an MCA from Chandigarh University in 2023, I’ve continued to fuel my curiosity by writing technical articles and sharing practical MERN stack insights across platforms. Whether it’s building polished UIs, optimizing backend performance, or guiding a mentee through their first pull request, I’m driven by the power of community and continuous learning. Let’s connect! I'm open to collaborations, mentorship, or building something impactful together. Reach out to me at kumaripayal7488@gmail.com or visit my profile on Topmate.io.