问题
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 I can agree on, mainly because it can make the code hard to reuse.
However, in some cases I've found it hard to come up with a good alternative to instanceof. For example, say that I want to make a Real-Time-Strategy game. The game consists of obstacles, buildings and tanks, all placed on a grid and each entitity takes up exactly one unit in the grid. So I create the class Entity which is the superclass of the classes Obstacle, Building and Tank. 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.
My only attempt as an alternative of using instanceof was to use the design pattern Visitor. The visitor gets accepted by an entity (entity->acceptVisitor(visitor))
which in turn calls one of the methods visitor->visitObstacle(this)
, visitor->visitBuildig(this)
or visitor->visitTank(this)
.
This, however, forced me to create a lot of visitors, almost one new for every single task that I wanted to make on entities. Another problem is that in many cases the visitor calls the same method on the entity, no matter what class it is constructed from. This could for example happen when an entity wants to check if another entity is stationary or not:
Python code:
class StationaryEntityGatherVisitor:
def __init__(self):
self.stationaryEntities = []
def visitObstacle(self, obstacle):
self._addIfStationary( obstacle )
def visitBuildig(self, building):
self._addIfStationary( building )
def visitTank(self, tank):
self._addIfStationary( tank )
def _addIfStationary(self, entity):
if entity.isStationary():
self.stationaryEntities.append( entity )
def getStationaryEntities():
return self.stationaryEntities
I could, of course, let the entity in this case just ask another entity if it is stationary directly instead of letting a visitor do that. But in that case I would not be consistent on checking properties of entities. To let the method of asking entities about some property (directly or through a visitor) vary, depending on if I need to check the entities type or not, would, in my opinion, seem like a pretty odd design.
So, do you have any other alternative to using instanceof in the problem described above?
Thanks! Martin
回答1:
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.
回答2:
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...
回答3:
In general, polymorphism is the way to avoid unnecessary instanceof operator.
回答4:
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.
来源:https://stackoverflow.com/questions/5721622/alternative-to-instanceof