I’m wrting something that look like this (of course its a bit more complex than this sample):
public class DoOnAll {
private List<IActionPerformer> actionPerformers;
public DoOnAll(List<IActionPerformer> actionPerformers) {
this.actionPerformers = actionPerformers;
}
public void callFromSomeWhere(String path) {
File f = new File(path);
List<File> list = Arrays.asList(f.listFiles());
for (File file : list) {
for (IActionPerformer action : actionPerformers) {
action.perform(file);
}
}
}
}
public interface IActionPerformer {
public void perform(File file);
}
public class SomePerformer implements IActionPerformer {
public void perform(File file) {
if (getFileType(file) = ".txt") {
doSomething
}
}
}
I have 2 questions:
-
Should I move the condition in
SomePerformerto another method,boolean accept(File file)for example, and also add this method declartion to the interface?
If so, how would I “collect” all the accepted classes inDoOnAll? just go through theactionPerformerslist and add all the accepeted to another list and then go through the list of accepted and.performon them? Or is there another way usually used in the methodology? -
Which ways are there for injecting the
actionPerformrslist into the class?
I want to write independent implementations and define in a file, say xml file, which ones to inject into the list.
In answer to your second question, you should look into dependency injection. Java has a few good frameworks that can do this for you, for example:
Spring in particular allows you to define your application’s components and dependencies in XML files. For examples see:
This last link has a subsection on constructor injection: creating java objects with dependencies supplied to their constructors, as your class
DoOnAllrequires.