3

我正在设计一个 2D 游戏来练习 Java 和面向对象编程(我正在使用 JSFML 库,如果有帮助的话),我对如何最好地设计以下内容有疑问:

我正在使用的库提供了一个Drawable由可见游戏元素(玩家、敌人、背景等)实现的界面。我也有一个RenderWindow我将在其上绘制Drawable对象。

事情是这样的,RenderWindow有一个在当前Window上draw(Drawable d)绘制对象的方法,而对象有一个在传递的上绘制当前对象的方法。DrawableDrawabledraw(RenderWindow r)DrawableRenderWindow

如果他们做的事情基本相同,我应该使用哪一个?为什么?我应该考虑什么来决定?我使用 HashMap 来存储Drawable对象。我应该将 HashMap 中的 传递RenderWindowDrawables还是将 HashMap中的 传递DrawablesRenderWindow?任何建议表示赞赏。

4

1 回答 1

1

One line answer to your question would be
Java language does not support double dispatch mechanism.

What to do: The library expects you to override these methods but never call them. I haven't used the library but from some experience with game engines, I guess the application will call the RenderWindow's draw and it will eventually make calls to all Drawable's draw methods. (Collection of Drawables will be maintained by RenderWindow.

Why: Java dynamically calls the method by checking the class of object on which the method being called (not by checking reference). This is called (as you probably know) dynamic dispatch.
But the method's arguments are selected by only checking reference (not by class of actual object passed as argument.)
Here, by forcing dynamic dispatch twice (by making two methods for same purpose), the library developers have indirectly implemented double dispatch.

In future, you might want to extend both Drawable and RenderWindow. If you had draw method in only Drawable, you can't have separate draw for each child of RenderWindow. Double dispatch solves this problem.

Hope this helps.

于 2013-12-19T17:50:51.197 回答