Alternative to instanceof?

后端 未结 4 672
清歌不尽
清歌不尽 2021-01-07 07:17

I\'ve heard that it is bad design to use instanceof or equivalent (http://www.javapractices.com/topic/TopicAction.do?Id=31, when should we use instanceof and when not) which

4条回答
  •  太阳男子
    2021-01-07 07:54

    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.

提交回复
热议问题