• Post Reply Bookmark Topic Watch Topic
  • New Topic

1. interface 60 implementations, any good ide out there to do this the best way.  RSS feed

 
Frank Jacobsen
Ranch Hand
Posts: 358
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How do i do this in the best way ?

I have 1. interface with one method.

I Will have 60 Implementations, from the "Name" i can see what class i will call.

I can make 60 if's or maybe a switch, but this is not nice.

Maybe a Class.forName ? , i can decide the name off the String Name thats the first parameter to my method.

Any good ideas out there ?




Frank
 
Paul Beckett
Ranch Hand
Posts: 96
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
60 conditions is a lot to do with Ifs/switch.

Think what you are really looking for is the Factory design pattern. I'd do it using reflection and Class.forname. Can't remember the method signature but there is one in Class (perhaps asSubclass??) that allows you to do the cast of the Class without compiler warnings.
 
Ed Ward
Ranch Hand
Posts: 147
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I believe you are on the right track by using Class.forName(name);
As long as "name" is the fully qualified class name and implements the one interface all you need to do is cast the returned Object to the interface name.
No need for 60 ifs or a switch statement.
This design also promotes ease of maintenance and security. The design pattern it implements escapes me at the moment but I want to say AbstractFactory.
 
Frank Jacobsen
Ranch Hand
Posts: 358
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, it helps me a lot
 
Frank Jacobsen
Ranch Hand
Posts: 358
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Here is a little piece of code that works, maybe others can use this code:



Thanks again

Frank
 
Paul Beckett
Ranch Hand
Posts: 96
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think that solution will work ok but does delve deeper into the reflection API than I think you need to go. Also it will probably result in compile time warnings in your code.

The solution I was thinking of was more akin to the following:


The main differences are that your code allows you to invoke a method with signature "evaluate(Kunde)" on any Object. Mine will only return instances of A so will rely on polymorphism for method invocation. Therefore my solution is based upon the assumption that all of your implementation classes will extend or implement a common base class or interface.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!