Observer Design Pattern in Java with Examples | Beginner to Advanced Guide

Reading Time: 14–16 minutes

The Observer Design Pattern is a behavioral design pattern that defines a one-to-many dependency between objects. When one object changes its state, all its dependent objects are automatically notified and updated.

This pattern is widely used in event-driven systems, messaging systems, UI frameworks, and notification services.

This tutorial explains the Observer pattern from beginner to advanced level with simple explanations, real-world examples, step-by-step implementation, and interview-level concepts.

What is Observer Design Pattern

The Observer pattern establishes a relationship where one object (called Subject) maintains a list of dependents (called Observers) and automatically notifies them when its state changes.

Simple definition:

When one object changes, all subscribed objects get notified automatically.

Why Do We Need Observer Pattern

In many applications, multiple components depend on a single object’s state.

Problem Without Observer Pattern

Suppose we have a YouTube channel system where subscribers must be notified whenever a new video is uploaded.


package com.codekatha;

class YouTubeChannel {

    public void uploadVideo() {
        System.out.println("New video uploaded");
        // manually notify each subscriber
    }
}

If we manually notify subscribers, the channel becomes tightly coupled with subscriber logic.

Problems in This Approach

Tight coupling between channel and subscribers
Hard to add new subscribers
Difficult to manage notifications
Poor scalability

We need a way where subscribers can register and automatically receive updates.

Solution – Observer Pattern

The Observer pattern allows subscribers to register themselves with the subject. When the subject’s state changes, it automatically notifies all registered observers.

Key Idea Behind Observer Pattern

Subject maintains list of observers
Observers subscribe to subject
Subject notifies observers on state change

Structure of Observer Pattern

Subject Interface → Register, remove, notify methods
Concrete Subject → Maintains observer list
Observer Interface → Update method
Concrete Observer → Implements update behavior

Step-by-Step Observer Pattern Implementation

Step 1 – Create Observer Interface


package com.codekatha;

interface Subscriber {
    void update(String videoTitle);
}

Step 2 – Create Concrete Observer


package com.codekatha;

class YouTubeSubscriber implements Subscriber {

    private String name;

    public YouTubeSubscriber(String name) {
        this.name = name;
    }

    public void update(String videoTitle) {
        System.out.println(name + " notified about new video: " + videoTitle);
    }
}

Step 3 – Create Subject Interface


package com.codekatha;

interface Channel {

    void subscribe(Subscriber subscriber);

    void unsubscribe(Subscriber subscriber);

    void notifySubscribers();
}

Step 4 – Create Concrete Subject


package com.codekatha;

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

class YouTubeChannel implements Channel {

    private List<Subscriber> subscribers = new ArrayList<>();
    private String videoTitle;

    public void subscribe(Subscriber subscriber) {
        subscribers.add(subscriber);
    }

    public void unsubscribe(Subscriber subscriber) {
        subscribers.remove(subscriber);
    }

    public void uploadVideo(String title) {
        this.videoTitle = title;
        notifySubscribers();
    }

    public void notifySubscribers() {
        for (Subscriber subscriber : subscribers) {
            subscriber.update(videoTitle);
        }
    }
}

Step 5 – Client Code


package com.codekatha;

class ObserverDemo {

    public static void main(String[] args) {

        YouTubeChannel channel = new YouTubeChannel();

        Subscriber user1 = new YouTubeSubscriber("Aman");
        Subscriber user2 = new YouTubeSubscriber("Rahul");

        channel.subscribe(user1);
        channel.subscribe(user2);

        channel.uploadVideo("Observer Design Pattern Explained");
    }
}

What We Achieved Using Observer Pattern

Loose coupling between subject and observers
Dynamic subscription and unsubscription
Automatic notification system
Improved scalability

Real-Life Examples of Observer Pattern

YouTube notifications
Email subscription systems
Stock market price updates
Weather alert systems
Event listeners in GUI applications

Push vs Pull Model in Observer

Push Model

Subject sends complete data to observers.

Pull Model

Subject notifies observers, and observers pull required data.

Observer vs Publish-Subscribe

Observer → Direct dependency between subject and observers.
Publish-Subscribe → Uses message broker between publisher and subscribers.

Advantages of Observer Pattern

Promotes loose coupling
Supports dynamic relationships
Easy to extend
Follows Open Closed Principle

Disadvantages of Observer Pattern

Memory leaks if observers not removed properly
Unexpected updates if poorly designed
Can become complex with many observers

When Should You Use Observer Pattern

When multiple objects depend on one object
When automatic updates are required
When implementing event-driven systems
When building notification systems

Real-World Usage in Java

java.util.Observer (deprecated)
EventListener in Swing
Spring ApplicationEvent
Reactive programming frameworks

Common Interview Questions on Observer Pattern

What problem does Observer solve?
Difference between Observer and Pub-Sub?
Push vs Pull model?
Real-world example of Observer?

Simple Summary

Observer pattern creates one-to-many dependency.
Observers register with subject.
Subject notifies observers on state change.
Promotes loose coupling and scalability.

Conclusion

The Observer Design Pattern is essential for building event-driven and notification-based systems. It simplifies communication between components while maintaining loose coupling.

Comments

Popular Posts on Code Katha

Java Interview Questions for 10 Years Experience

Sql Interview Questions for 10 Years Experience

Spring Boot Interview Questions for 10 Years Experience

Java interview questions - Must to know concepts

Visual Studio Code setup for Java and Spring with GitHub Copilot

Spring AI with Ollama

Data Structures & Algorithms Tutorial with Coding Interview Questions

Spring Data JPA

Topological Sort in Graph

Bit Manipulation and Bit Masking Concepts