用Java进行多态调度 [英] Polymorphically Dispatching in Java
问题描述
在下文中,我希望EventHandler以一种方式处理EventA,以另一种方式处理EventB,以及另一种方式处理任何其他事件(EventC,EventD)。 EventReceiver仅接收对Event的引用并调用EventHandler.handle()。当然,总是被调用的版本是EventHandler.handle(事件事件)。
In the following, I want EventHandler to handle EventA one way, EventB another way, and any other Events (EventC, EventD) yet another way. EventReceiver receives only a reference to an Event and calls EventHandler.handle(). The version that always gets called, of course, is EventHandler.handle(Event event).
不使用instanceOf,是否有一种多态分派的方法(可能通过另一种方法)在EventHandler或泛型中)到适当的句柄方法?
Without using instanceOf, is there a way to polymorphically dispatch (perhaps via another method in EventHandler or generics) to the appropriate handle method?
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);
}
}
推荐答案
声音类似于应用访客模式(的变体)的情况。 (在主流OO语言中,例如C ++,C#和Java,方法是单一调度,即一次只能在一种类型上进行多态。访问者允许实现双重调度。)
Sounds like a case for applying (a variant of) the Visitor pattern. (In mainstream OO languages such as C++, C# and Java, methods are single dispatch, i.e. can only be polymorphic on one type at a time. Visitor allows one to implement double dispatch.)
然而,这要求您能够修改事件
类,并创建依赖关系从事件
到(基本接口) EventHandler
。
This however requires that you be able to modify the Event
classes as well, and creates a dependency from Event
s to (a base interface of) EventHandler
.
class EventA extends Event {
public handleBy(EventHandler eh) {
eh.handleEventA(this);
}
}
class EventB extends Event {
public handleBy(EventHandler eh) {
eh.handleEventB(this);
}
}
class EventHandler {
void handleEventA(EventA event) {
System.out.println("Handling EventA");
}
void handleEventB(EventB event) {
System.out.println("Handling EventB");
}
void handle(Event event) {
event.handleBy(this);
}
}
这篇关于用Java进行多态调度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!