Observer Design Pattern

Loading...
By technoayan
Design-PatternObserver
Observer Design Pattern
0 min read
LLD
Design-Pattern
Observer

Observer Design Pattern

Learn how the Observer Design Pattern helps in building event-driven systems in Java. This guide explains the concept with real-world examples, clean code, and best practices.

πŸ‘€ Observer Design Pattern in Java

The Observer Pattern is a behavioral design pattern where one object (subject) notifies a group of dependent objects (observers) whenever its state changes.

It’s widely used in:

  • UI event handling (e.g., button clicks)
  • Notification systems
  • Real-time updates (chat, stock prices, etc.)

🎯 Real-Life Analogy

πŸ“± Imagine a YouTube channel:

  • You're the Subscriber (Observer)
  • The Channel is the Subject

Whenever a new video is uploaded, you get notified. That's the Observer pattern in action!


πŸ”§ When to Use Observer Pattern?

  • When multiple objects need to stay updated with changes in one object.
  • When you're building event-driven systems.
  • When you want to decouple subjects and their dependents.

πŸ”₯ Example – Notification System

Let’s build a system where users get notified when a new message is published.


πŸ”Έ Step 1: Create Observer Interface

β˜•JAVA
interface Observer {
    void update(String message);
}

πŸ”Έ Step 2: Concrete Observers (Subscribers)

β˜•JAVA
class EmailSubscriber implements Observer {
    private String email;

    public EmailSubscriber(String email) {
        this.email = email;
    }

    public void update(String message) {
        System.out.println("Email to " + email + ": " + message);
    }
}

class SMSSubscriber implements Observer {
    private String phoneNumber;

    public SMSSubscriber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }

    public void update(String message) {
        System.out.println("SMS to " + phoneNumber + ": " + message);
    }
}

πŸ”Έ Step 3: Create Subject Interface

β˜•JAVA
interface Subject {
    void subscribe(Observer o);
    void unsubscribe(Observer o);
    void notifyObservers(String message);
}

πŸ”Έ Step 4: Concrete Subject (Publisher)

β˜•JAVA
import java.util.ArrayList;
import java.util.List;

class MessagePublisher implements Subject {
    private List<Observer> observers = new ArrayList<>();

    public void subscribe(Observer o) {
        observers.add(o);
    }

    public void unsubscribe(Observer o) {
        observers.remove(o);
    }

    public void notifyObservers(String message) {
        for (Observer o : observers) {
            o.update(message);
        }
    }
}

πŸ”Έ Step 5: Test the System

β˜•JAVA
public class ObserverDemo {
    public static void main(String[] args) {
        MessagePublisher publisher = new MessagePublisher();

        Observer emailUser = new EmailSubscriber("ayan@xyz.com");
        Observer smsUser = new SMSSubscriber("9876543210");

        publisher.subscribe(emailUser);
        publisher.subscribe(smsUser);

        publisher.notifyObservers("πŸ“’ New Blog Post on Observer Pattern!");

        publisher.unsubscribe(emailUser);

        publisher.notifyObservers("πŸ“’ New Update: SOLID Principles Refreshed!");
    }
}

βœ… Output

Email to ayan@xyz.com: πŸ“’ New Blog Post on Observer Pattern! SMS to 9876543210: πŸ“’ New Blog Post on Observer Pattern! SMS to 9876543210: πŸ“’ New Update: SOLID Principles Refreshed!

πŸ“Œ Key Concepts

| Concept | Description | | -------------- | -------------------------------------- | | Subject | Maintains list of observers | | Observer | Gets notified of changes | | Loose Coupling | Subject doesn’t care what observers do | | Flexibility | Can add/remove observers at runtime |


πŸ” Real-Time Use Cases

  • βœ… UI components (React/Angular bindings)
  • βœ… Event buses or messaging systems
  • βœ… Chat applications
  • βœ… Stock ticker updates
  • βœ… File system change monitors

🧠 Interview Q&A

Q: What type of pattern is Observer? A: Behavioral

Q: What's the difference between Observer and Publisher-Subscriber? A:

  • Observer is tightly coupled, usually direct references.
  • Pub/Sub uses a message broker (like Kafka, RabbitMQ).

Q: Is Observer pattern used in Java libraries? A: Yes! For example:

  • java.util.Observer (deprecated, but historically used)
  • Event listeners in Swing/AWT (UI frameworks)

🧠 Observer vs Strategy vs Decorator

| Pattern | Purpose | | --------- | -------------------------------- | | Observer | Notify many on state change | | Strategy | Choose behavior at runtime | | Decorator | Add responsibilities dynamically |


πŸ“š Summary

  • βœ… Observer helps you notify multiple objects when state changes.
  • πŸ”— Promotes loose coupling between subject and observers.
  • πŸ”„ Easy to extend, reuse, and manage listeners.
  • 🧩 Perfect for real-time, event-driven systems.

Thanks for reading!

technoayan

Author & Tech Enthusiast

"Keep learning, keep growing, and keep sharing knowledge with the world."

Rate This Post

Share your thoughts and help others discover great content

Sign in to rate this post and share your feedback

Community Rating

No ratings yet. Be the first to rate this post!

Comments (0)

Leave a Comment

No comments yet. Be the first to share your thoughts!

TechnoBlogs

by Ayan Ahmad

Exploring the world of technology through insightful articles, tutorials, and personal experiences. Join me on this journey of continuous learning and innovation.

Stay Updated

Built With

React
Next.js
Tailwind
Firebase
Powered by Coffee

Every line of code written with love and caffeine β˜•

Β© 2025 TechnoBlogsβ€’Made withbyAyan Ahmad

Open source β€’ Privacy focused β€’ Built for developersβ€’Privacy Policyβ€’Terms of Service