Java 中的多态调度
2022-09-03 14:20:53
在下文中,我希望 EventHandler 以一种方式处理 EventA,以另一种方式处理 EventB,以及任何其他事件(EventC、EventD) 以另一种方式处理。EventReceiver 仅接收对 Event 的引用并调用 EventHandler.handle()。当然,总是被调用的版本是EventHandler.handle(Event event)。
如果不使用 instanceOf,有没有办法多态调度(可能通过 EventHandler 或泛型中的另一种方法)到适当的句柄方法?
class EventA extends Event {
}
class EventB extends Event {
}
class EventC extends Event {
}
class EventD extends Event {
}
class EventHandler {
void handle(EventA event) {
System.out.println("Handling EventA");
}
void handle(EventB event) {
System.out.println("Handling EventB");
}
void handle(Event event) {
System.out.println("Handling Event");
}
}
class EventReceiver {
private EventHandler handler;
void receive(Event event) {
handler.handle(event);
}
}