Fundamentals 11 min read

Understanding Observer vs Listener Patterns with Java Code and Spring Events

This article explains the observer and listener design patterns, shows how to implement both in Java with concrete code examples, compares their differences, and demonstrates how Spring's event mechanism is a practical application of these patterns.

Senior Brother's Insights
Senior Brother's Insights
Senior Brother's Insights
Understanding Observer vs Listener Patterns with Java Code and Spring Events

Introduction

The observer pattern establishes a one‑to‑many relationship between a subject and its observers. When the subject’s state changes it notifies all registered observers. This mechanism underlies many event‑driven frameworks, such as Spring’s application event system.

Why Use Design Patterns

Design patterns provide reusable solutions that improve readability, reliability, and maintainability. They promote low coupling and low dependency, making code easier to extend. The observer pattern achieves decoupling and asynchronous communication between components.

Observer Pattern Definition

A Subject maintains a collection of Observer objects. The subject provides methods to register observers and to broadcast a notification (often an arbitrary payload) to all observers.

Observer pattern diagram
Observer pattern diagram

Java Implementation

Define the core interfaces and concrete classes:

public interface Subject {
    void registerObserver(Observer observer);
    void notifyObservers(Object msg);
}
public interface Observer {
    void update(Object msg);
}
public class ConcreteSubject implements Subject {
    private List<Observer> observers = new ArrayList<>();

    @Override
    public void registerObserver(Observer observer) {
        observers.add(observer);
    }

    @Override
    public void notifyObservers(Object msg) {
        for (Observer observer : observers) {
            observer.update(msg);
        }
    }
}
public class ConcreteObserver implements Observer {
    @Override
    public void update(Object msg) {
        System.out.println("ConcreteObserver received: " + msg);
    }
}
public class ObserverTest {
    public static void main(String[] args) {
        Subject subject = new ConcreteSubject();
        Observer observer = new ConcreteObserver();
        subject.registerObserver(observer);
        subject.notifyObservers("Message from Subject");
    }
}

Running ObserverTest prints the message, confirming that the observer receives the notification without any knowledge of the subject’s internal logic.

Listener Pattern (Event‑Based Observer)

The listener pattern is a specialization of the observer pattern where the notification carries an explicit Event object that encapsulates additional data and type information. This makes each event polymorphic and allows richer payloads.

public class Event {
    private String data;
    private String type;

    public Event(String data, String type) {
        this.data = data;
        this.type = type;
    }
    // getters and setters omitted for brevity
}
public interface Listener {
    void onClick(Event event);
}
public class ListenerA implements Listener {
    @Override
    public void onClick(Event event) {
        System.out.println("Triggered event, type:" + event.getType() + ", data:" + event.getData());
    }
}
public class ListenerSupport {
    private List<Listener> listeners = new ArrayList<>();

    public void addListener(Listener listener) {
        listeners.add(listener);
    }

    public void triggerEvent(Event event) {
        for (Listener listener : listeners) {
            listener.onClick(event);
        }
    }
}
public class EventTest {
    public static void main(String[] args) {
        Listener listener = new ListenerA();
        ListenerSupport support = new ListenerSupport();
        support.addListener(listener);
        support.triggerEvent(new Event("dataA", "typeA"));
    }
}

The output demonstrates that the listener receives both the event type and data, illustrating how the listener pattern enriches the notification.

Observer vs. Listener Comparison

Both patterns share the same registration‑notification mechanism. The listener pattern adds an Event object, giving each notification its own state and enabling polymorphic handling. Consequently, the listener pattern can be viewed as a more abstract, flexible variant of the observer pattern.

Observer vs Listener comparison diagram
Observer vs Listener comparison diagram

Spring’s Event Mechanism (Real‑World Application)

Spring implements the observer pattern through its event‑driven model. The four core roles are:

Event : All events extend ApplicationEvent, which itself extends JDK’s EventObject. Built‑in events include ContextRefreshedEvent, ContextStartedEvent, etc.

Event Listener : Implement ApplicationListener<E extends ApplicationEvent> and override onApplicationEvent(E event) to handle the event.

Event Source : ApplicationContext acts as the publisher; it implements ApplicationEventPublisher with the method publishEvent(Object event).

Event Multicaster : ApplicationEventMulticaster registers listeners and broadcasts events to them.

Conclusion

The listener pattern is essentially a renamed and slightly extended observer pattern where the notification carries an explicit event object. Spring’s application event system is a classic, production‑grade example of this pattern, demonstrating how design patterns enable decoupled, reusable communication in modern Java applications.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Design PatternsJavaObserver PatternEvent-drivenSpring EventsListener Pattern
Senior Brother's Insights
Written by

Senior Brother's Insights

A public account focused on workplace, career growth, team management, and self-improvement. The author is the writer of books including 'SpringBoot Technology Insider' and 'Drools 8 Rule Engine: Core Technology and Practice'.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.