Below I am trying to explain the problem with an example.
We have a Caller.java
Caller.java : which calls the series of Actors to perform certain steps in sequence.
Actor.java : Abstract class containing action() method
ActorOne.java : Implements the action() method
ActorTwo.java : Implements the action() method
ActorThree.java : Implements the action() method
At runtime, based on a task to accomplish, a collection of classes is prepared inside Caller.java and instantiated using the Reflection.
Actor.java: callActions(){
Class[] classes = [ActorOne.class, ActorTwo.class]
for(Class clazz : classes){
Actor actor = (Actor) clazz.newInstance();
actor.action();
}
}
In certain situation, which I know runtime inside the callActions.java, I need to inform the ActorTwo to peform the action method differently.
My solution is to pass that flag to the ActorTwo object using Reflection API and inside the action() method put if/else to perform the flag specific action.
Is there a better way to design the solution, so that I can avoid the if/else within the ActorTwo.action() method?
Best Regards
Another option is to make the
action()
method take an array of arguments (likemain(...)
does). That way ActorTwo could check the arguments to see if its in the special case, whereas the other Actors could just ignore the input.This formation gives you the most flexibility going forward with adding extra cases to any actors.