Observer Design Pattern

By technoayanβ€’
0views
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
SubjectMaintains list of observers
ObserverGets notified of changes
Loose CouplingSubject doesn’t care what observers do
FlexibilityCan 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
ObserverNotify many on state change
StrategyChoose behavior at runtime
DecoratorAdd 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."

Show Some Love

Let the author know you enjoyed this content

0
people like this

Sign in to show your appreciation

Share This Post

Help others discover this content

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!

More in LLD

Comments (0)

Leave a Comment

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