Observer Design Pattern

Observer Design Pattern

One sunny afternoon, Alice and Bob decided to meet at their favorite park.

Alice: Hi Bob, how's everything going?

Bob: Hey Alice! I'm good. Just enjoying the weather. How about you? Any new design patterns from your system design classes?

Alice: Yes, today I learned about the Observer Design Pattern.

Bob: Observer? What's that all about?

Alice: The Observer is a behavioral design pattern that allows an object, known as the subject, to maintain a list of its dependents, called observers, and notify them of any state changes, usually by calling one of their methods.

Bob: Can you give me a real-world example?

Alice: Sure! Let's imagine a scenario where you run a news agency. You want to notify your subscribers whenever there's breaking news. Here, the news agency is the subject, and the subscribers are the observers.

Bob: That sounds interesting. How would you implement this in code?

Alice: Let's dive into it. We'll define an interface for our observers and our subject. The subject will maintain a list of observers and notify them when there's an update.

Observer Interface:

public interface Observer {
    void update(String news);
}        

Concrete Observer Implementations:

public class Subscriber implements Observer {
    private String name;

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

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

Subject Interface:

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

public interface Subject {
    void subscribe(Observer observer);
    void unsubscribe(Observer observer);
    void notifyObservers();
}        

Concrete Subject Implementation:

public class NewsAgency implements Subject {
    private List<Observer> subscribers;
    private String latestNews;

    public NewsAgency() {
        this.subscribers = new ArrayList<>();
    }

    @Override
    public void subscribe(Observer observer) {
        subscribers.add(observer);
    }

    @Override
    public void unsubscribe(Observer observer) {
        subscribers.remove(observer);
    }

    @Override
    public void notifyObservers() {
        for (Observer subscriber : subscribers) {
            subscriber.update(latestNews);
        }
    }

    public void setLatestNews(String news) {
        this.latestNews = news;
        notifyObservers();
    }
}        

Main Class:

public class Main {
    public static void main(String[] args) {
        NewsAgency newsAgency = new NewsAgency();

        Subscriber subscriber1 = new Subscriber("Alice");
        Subscriber subscriber2 = new Subscriber("Bob");

        newsAgency.subscribe(subscriber1);
        newsAgency.subscribe(subscriber2);

        newsAgency.setLatestNews("Breaking News: New Observer Design Pattern Tutorial Released!");

        newsAgency.unsubscribe(subscriber1);

        newsAgency.setLatestNews("Update: Observer Design Pattern is now easier to learn!");
    }
}        

Alice: In this example, NewsAgency is the subject, and Subscriber is the observer. The NewsAgency maintains a list of subscribers and notifies them whenever there is a new update by calling their update method.

Bob: So, whenever NewsAgency updates its news, all subscribed Subscriber instances get notified automatically?

Alice: Exactly. This way, you can have multiple subscribers, and they all get notified without the NewsAgency needing to know the details of each subscriber.

Bob: What if a subscriber wants to unsubscribe from the notifications?

Alice: The unsubscribe method in the NewsAgency class allows you to remove a subscriber from the list. As you can see in the main method, after the first news update, Alice unsubscribes from further updates, so only Bob receives the second update.

Bob: This is really useful. I can see how it would be helpful in various scenarios like event handling, user interface updates, and more.

Alice: Yes, it's a very versatile pattern. Understanding and using design patterns like the Observer can greatly enhance the maintainability and scalability of your code.

Bob: Thanks for the explanation, Alice. I'll definitely keep this in mind for my next project.

Alice: You're welcome, Bob. Happy coding!


As they finish their conversation, Alice and Bob decide to take a walk around the park, enjoying the rest of their sunny afternoon. They know they'll have more design patterns to discuss in the future.


Until then, signing off with ? Ganesh.

要查看或添加评论,请登录

Ganesh Manchi的更多文章

  • Facade Design Pattern

    Facade Design Pattern

    Alice and Bob are watching a movie at Bob's place, enjoying the latest action flick on Bob's impressive home theater…

  • Factory Design Pattern

    Factory Design Pattern

    One sunny morning, Alice and Bob met at a bustling factory. Alice: Hi Bob, what brings you to this factory today? Bob:…

  • Decorator Design Pattern

    Decorator Design Pattern

    One sunny afternoon, Alice and Bob found themselves at their favorite coffee shop. Alice: Hi Bob, how's your day going?…

    2 条评论
  • Strategy Design Pattern

    Strategy Design Pattern

    Bob came to Alice's house, and they have been playing Mortal Kombat for two hours. Alice: Hey Bob, we've played a lot…

  • Builder Design Pattern

    Builder Design Pattern

    Alice and Bob find themselves at a construction site once again. Alice : Hi Bob, what are you doing in this…

  • Singleton Design Pattern

    Singleton Design Pattern

    One day, Alice and Bob meet at a coffee shop. Alice : Hi Bob, how are you doing? Bob : I'm good.

    2 条评论
  • Coding culture in colleges :(

    Coding culture in colleges :(

    Hello, World! Note: If your college has a good coding culture, then skip this article. I want to share what I've…

    5 条评论
  • DSA vs CP

    DSA vs CP

    Hello World! One of the most confusing topics that often crosses our minds is the choice between Data Structures and…

社区洞察

其他会员也浏览了