In my app there are objects representing tasks (stored in the DB). There will also be objects that have the actual implementation of a task (some business logic) - let's call them runners. So runners could i.e. implement the following interface:
public interface Runner<T> {
void run(T task);
}
Given a task object, I need some nice way to create/get a runner so that I can run it.
I'd prefer to avoid something like
if(task instance of DoSomethingTask) {
return new DoSomethingTaskRunner();
} else if(task instance of DoSomethingElseTask) {
return new DoSomethingElseRunner();
}
because then whenever I create a new runner I also need to remember to add another if/else to the above block. It would be nice to just automatically get the runner that implements
Runner<myTask.getClass()> // pseudocode ;)
A nice way of doing this would be to make the Tasks have a "getRunner" method (adding a new Task I need to implement the method so I cannot forget it) but unfortunately due to project dependencies my Task objects cannot know anything about Runners.
Any ideas regarding how to do it in a nice way?
Btw.: I'm using Spring so it would be even nicer to get a Runner bean based on the passed task.