Daniel Pitts <newsgroup.spamfilter@virtualinfinity.net> writes:
Yes, but often times it is a sign of a design flaw. What does this
hierarchy give you that doesn't involve implementing methods
differently? You shouldn't have to use instanceof or .getClass() in
order to handle the subclasses in a useful way.
You can read my mind!
Indeed, I might use ?instanceof? with these classes.
Think of a graph of interconnected components
(so that a component might have ?neighbor components?),
including - for example's sake - a clock component.
The clock component then might contain code like:
public void process( final Command command )
{
if( command instanceof clockCommand )
{
/* This command is intended for me! Let me process it: */
if( command instanceof quitClockCommand )
{ /* Some party wants me to quit */ }
else if( command instanceof adjustClockCommand )
{ /* I should adjust myself now */ }
else { /* There are only these two clock commands,
so this is unexpected. */ }
else
{ /* This command is just passing-through, I will broadcast
it to my neighbors, maybe it is intended for one of them. */
broadcastToNeighbors( command );
/* Yes: if they do not know the command, and broadcast it,
too, this will give an endless loop of command reposts.
The real code will address this, the code posted here into
Usenet is simplified. */ }}
I have a guilty conscience for the use of ?instanceof?.
But how can this be implemented in a better way in this case?
Sounds like you need a different design. You could possibly use a
visitor pattern, eg. command.visit(this),
That way, the command is responsible for known what method to call.
all of that (including the broadcast/neighbor logic). The controller
whichever).
events to actions, it's design fits your scenario fairly well.