I've got such an interface:
public interface Listener {
void onA();
void onB();
void onC();
}
And there is a list of listeners/observers:
List<Listener> listeners = new ArrayList<Listener>();
How can I easily inform all listeners, that A, B, C occurred via Listener.onA(), Listener.onB(), Listener.onC()?
Do I have to copy-paste iteration over all listeners at least three times?
In C++ I would create such a function:
void Notify(const std::function<void(Listener *listener)> &command) {
for(auto &listener : listeners) {
command(listener);
}
}
And pass lambda for each of methods:
Notify([](Listener *listener) {listener->onA();});
or
Notify([](Listener *listener) {listener->onB();});
or
Notify([](Listener *listener) {listener->onC();});
Is there a similar approach in Java?