1

I need a design pattern to pass arguments to a subclass, however the arguments differ.

1) Unlimited instanceof checks: Problems: a) slow b) not readable.

Component a ;
if ( a instanceof SimpleComponent)
{
   (SimpleComponent)a.do();
}
else if ( a instanceof UnitComponent)
{
   (UnitComponent)a.do( unit );
}
else if ( a instanceof BuildingComponent)
{
   (BuildingComponent)a.do( building );
}

1a) Use Setter: Same as above instead do(X), call set(X), requires unlimited instanceof checks.

2) Huge switch statement: Problems: a) we still have to cast instances. b) not readable.

3) pass the variables on constructor: Problems: Cannot change that variable again in the lifetime of application, that would require a call to a specific unknown .set(X) Method.

4) Put all unreleted variables to superclass:

   Component
   {
     Unit unit;
     Building building;
     String i_can_pass_strings_0;
     String i_can_pass_strings_1;
     String i_can_pass_strings_2;
     int    i_am_allowed_to_pass_a_single_int_now;
   }

This is like using global variables for the shake of passing variables between functions. You will end with a class with 200-300 unrelated variables, problems with garbage collection. Also you must be trolling for even thinking it, the class ends as a big unreadable garbage bin.

5) The above Component class renamed to ComponentOptions (it still is a garbage bin).

interface Component
{
   do ( ComponentOptions );
}

solution: at least now i don't have to think how i call do(); it is called the same way.

problems: a) instead of the caller deciding what variables to pass, the receiver subclass has to decide how to read the variables. In this case we use ComponentOptions which is our garbase disposal bin.

6) Component pattern: has/get Component.

class UnitComponent implement Component
{
   public void do( ComponentOptions componentOptions )
   {
      if ( hasComponent( Unit.class )
      {
         Unit unit = componentOptions.getComponent( Unit.class );
         doStuff( unit ) ;
      }
   }
}

a) readable

Question: 1) is there another design pattern to solve this problem, or is solution 6 the best way to solve this?

Max Max
  • 13
  • 2
  • To clarify: the caller has some variable `a` whose type is just `Component` and you don't know the (sub)class of the object that `a` references? Then you want to invoke the `do` method of `a`? But if you don't know the class, how do you know what to pass? – Ray Toal Jul 04 '12 at 19:53

1 Answers1

1

One of known substitutes of spamming instanceofs is Visitor pattern - take a look here: http://www.refactoring.com/catalog/replaceConditionalWithVisitor.html

you can also read this question Avoiding instanceof in Java

Community
  • 1
  • 1
dantuch
  • 9,123
  • 6
  • 45
  • 68
  • ok done, it works flawlessly, with visitor pattern i reduced my code size and it is definitely faster. – Max Max Jul 05 '12 at 06:22