模式,以弥补基于Java中的多态args缺乏运行时方法查找? [英] Patterns to compensate for lack of runtime method lookup based on polymorphic args in Java?
问题描述
似乎Java无法根据参数的运行时类型选择最合适的方法实现,如文档此处。概括示例:
It seems that Java can't choose the most appropriate method implementation based on the runtime type of an argument, as documented here. Recapitulating the example:
class Superclass {}
class Subclass extends Superclass {}
class Test {
public void aMethod(Superclass s) {...}
public void aMethod(Subclass s) {...}
}
执行Test类的哪种方法取决于引用的类型,而不是实例的类型。同样,基于链接的示例:
Which method of the Test class is executed is determined based on the type of the reference, not the type of the instance. Again, based on the linked examples:
Test aTest = new Test();
Superclass aSuper = new Subclass();
test.aMethod(aSuper);
aMethod(Superclass s)
那个执行,而不是 aMethod(子类s)
。
我试图在侦听器模式上创建一个变体,其中侦听器通过接口插入,并且侦听器具有为接口的子类定义的方法。
I was trying to create a variation on the listener pattern, where listeners 'plug in' via an interface, and the listeners have methods defined for subclasses of the interfaces.
作为我的意思的一个简单示例,说我正在构建一个可以插入功能的闹钟。
As a quick example of what I mean, say I'm building an alarm clock that can have functionality plugged in.
我想到的上面的实现看起来像一个接口 Event
,子类 WakeUpEvent
,接口 EventListener
需要实现句柄(事件evt)
。
The implementation for the above I had in mind would look like an interface Event
, with a subclass WakeUpEvent
, and an interface EventListener
requiring implementation of handle(Event evt)
.
我希望创建一个实现no-op 句柄的类(Event evt)
带有特定的句柄(WakeUpEvent evt)
如果听众想要处理那种类型的事件。
I hoped to create a class implementing a no-op handle(Event evt)
with a specific handle(WakeUpEvent evt)
if the listener wanted to deal with that type of event.
当然,这种方法不会按原样运作 - 显而易见的解决方案ion是运行时 instanceof
检查 - yuk。
Of course, this approach won't work as-is - the obvious solution is runtime instanceof
checks - yuk.
我是否可以使用任何模式或方法来获取行为我想要?
Are there any patterns or approaches that I can use to get the behaviour I want?
推荐答案
这些情况是我想到访客或双重调度模式。
These situations are when I think of Visitor or double dispatch pattern.
这篇关于模式,以弥补基于Java中的多态args缺乏运行时方法查找?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!