Alternative to instanceof?

扶醉桌前 提交于 2019-12-01 00:57:50

Forgetting about your Visitor solution for a second, and concentrating on just your requirement:

The grid consists of instances of Entity. During each update I want each tank to aim and shoot on an enemy tank within range. So, an easy way to do this would be for each tank to ask the grid for all entities within the tanks range and then iterate over all these entities and check if they are an instance of the class Tank.

Why not just filter the list directly?

targetablesInRange = filter(isTargetable, grid.itemsInRangeOf(self))

Instead of just Tanks, you should be asking about a property of entities that makes them a target. This could return false in the base class and be overridden by Tank and other classes that you introduce later that should be fired upon.

Well, have you considered iterating over all of the tanks to see if they're in range instead of all of the entities in range to see if they're tanks? Seems like it would save you a lot of time on both iteration and instanceof calls...

In general, polymorphism is the way to avoid unnecessary instanceof operator.

I do not know if you need to use Visitor to handle this behavior. Your case could be very easily accomplished by using general polymorphism. I was initially about to suggest a factory method and type variable, but the solution could be even simpler.

So you have a general Abstract Superclass. (Entity). So in this class you can define a method called hitByMissile() (or whatever). In your tank class, you can make hitByMissile, perform differently from lets say an Obstacle. Your code should not decide on how each entity behave. The behavior should be defined by the object itself. So you can just iterate over the entities and call the method.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!