LearnFrenzy
Sign in Take a free test

Interfaces · Interfaces Programs · Question 3

Event listeners with a functional interface in Java Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 3 Back to Exercise

Write an EventBus that lets listeners (a functional interface) subscribe to named events and publishes events to every subscriber; register lambdas and a class-based listener.

Solution
Main.java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@FunctionalInterface
interface Listener {
    void onEvent(String event, String data);
}

class EventBus {
    private final Map<String, List<Listener>> subs = new HashMap<>();
    void subscribe(String event, Listener l) { subs.computeIfAbsent(event, e -> new ArrayList<>()).add(l); }
    int publish(String event, String data) {
        List<Listener> ls = subs.getOrDefault(event, List.of());
        for (Listener l : ls) l.onEvent(event, data);
        return ls.size();
    }
}

class AuditLog implements Listener {
    final List<String> entries = new ArrayList<>();
    public void onEvent(String e, String d) { entries.add(e + ":" + d); }
}

public class Main {
    public static void main(String[] args) {
        EventBus bus = new EventBus();
        AuditLog audit = new AuditLog();
        bus.subscribe("order", (e, d) -> System.out.println("email: order " + d + " confirmed"));
        bus.subscribe("order", (e, d) -> System.out.println("sms: order " + d + " placed"));
        bus.subscribe("order", audit);
        bus.subscribe("refund", audit);
        System.out.println(bus.publish("order", "#1042") + " listeners");
        System.out.println(bus.publish("refund", "#0999") + " listener, " + bus.publish("login", "asha") + " for login");
        System.out.println(audit.entries);
    }
}

Output Verified by compiling and running

email: order #1042 confirmed
sms: order #1042 placed
3 listeners
1 listener, 0 for login
[order:#1042, refund:#0999]

Lambdas and a named class are interchangeable as Listener implementations – the Observer pattern.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

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

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links