I have this 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 tell all listeners that A, B, C occurred through Listener.onA() , Listener.onB() , Listener.onC() ?
Do I need to copy-paste iteration over all listeners at least three times?
In C ++, I would create a function like this:
void Notify(const std::function<void(Listener *listener)> &command) { for(auto &listener : listeners) { command(listener); } }
And skip lambda for each of the 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?
Dejwi source share