Write a Button class that keeps a list of Consumer<String> listeners and notifies them on click; register lambdas and a method reference, then click twice.
Solution
Main.java
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
class Button {
private final String label;
private final List<Consumer<String>> listeners = new ArrayList<>();
private int clicks;
Button(String label) { this.label = label; }
void onClick(Consumer<String> l) { listeners.add(l); }
void click() { clicks++; listeners.forEach(l -> l.accept(label + "#" + clicks)); }
}
public class Main {
static final List<String> AUDIT = new ArrayList<>();
static void audit(String event) { AUDIT.add(event); }
public static void main(String[] args) {
Button save = new Button("Save");
save.onClick(e -> System.out.println("saving... " + e));
save.onClick(e -> { if (e.endsWith("#2")) System.out.println("double-click detected"); });
save.onClick(Main::audit);
save.click();
save.click();
System.out.println("audit " + AUDIT);
}
}
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
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!