Skip to content

Instantly share code, notes, and snippets.

@beders
Last active December 8, 2015 13:35
Show Gist options
  • Save beders/3f7324691cd4250fb4d8 to your computer and use it in GitHub Desktop.
Save beders/3f7324691cd4250fb4d8 to your computer and use it in GitHub Desktop.
Examples for optional lambda parameters and polymorphism with default methods
package example;
import java.util.ArrayList;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
/**
* Created by beders on 7/7/15.
*/
public class BetterBus {
public static class Event {}
public static class Header {}
public interface BaseHandler {
default void dispatch(Event evt, Header header) {}
}
public interface EventHandler extends BaseHandler {
void handle(Event evt);
default void dispatch(Event evt, Header header) {
handle(evt); // ignore header
}
}
public interface EventAndHeaderHandler extends BaseHandler {
void handle(Event evt, Header header);
default void dispatch(Event evt, Header header) {
handle(evt, header);
}
}
List<BaseHandler> handlers = new ArrayList();
public void register(EventHandler handler) {
handlers.add(handler);
}
public void register(EventAndHeaderHandler handler) { handlers.add(handler); }
public void dispatch(Event event, Header header) {
handlers.forEach(handler -> handler.dispatch(event, header));
}
public static void main(String... args) {
BetterBus bus = new BetterBus();
bus.register(event -> System.out.println("I gots an event"));
bus.register((event,header) -> System.out.println("I gots an event w/ header"));
bus.dispatch(new Event(), new Header());
}
}
package example;
import java.util.ArrayList;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
/**
* Created by beders on 7/7/15.
*/
public class Bus {
public static class Event {}
public static class Header {}
List<Object> handlers = new ArrayList();
public void register(Consumer<Event> handler) {
handlers.add(handler);
}
public void register(BiConsumer<Event,Header> handler) {
handlers.add(handler);
}
public void dispatch(Event event, Header header) {
for (Object obj : handlers) {
if (obj instanceof Consumer) {
Consumer<Event> c = (Consumer<Event>) obj;
c.accept(event);
} else if (obj instanceof BiConsumer) {
BiConsumer<Event, Header> b = (BiConsumer<Event, Header>) obj;
b.accept(event, header);
}
}
}
public static void main(String... args) {
Bus bus = new Bus();
bus.register(event -> System.out.println("I gots an event"));
bus.register((event,header) -> System.out.println("I gots an event w/ header"));
bus.dispatch(new Event(), new Header());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment