This is a follow up of my earlier question.
I want to create a factory like approach to be able to call different methods depending on the type.
The following code works (note it is long but it is a very simplified version to show the structure. In reality for instance there won't be just one Person
added to the result list):
public class TestBuilder <T>{
private interface Processor <T> {
List<Person> process(T t, String firstName, String lastName, String id, String cc);
}
private class FooProcessor implements Processor <Foo> {
@Override
public List<Person> process(Foo foo, String firstName, String lastName, String id, String cc) {
System.out.println("processFoo");
Person p = new Person(firstName, lastName);
p.setId(foo.getId());;
return new ArrayList<>(Arrays.asList(p));
}
}
private class BarProcessor implements Processor <Bar> {
@Override
public List<Person> process(Bar bar, String firstName, String lastName, String id, String cc) {
System.out.println("processBar");
Person p = new Person(firstName, lastName);
p.setCc(bar.getCC());
return new ArrayList<>(Arrays.asList(p));
}
}
private Map<AnInterface<T>, Processor <T>> map = new HashMap<>();
private TestBuilder() {
map.put((AnInterface<T>) new Foo(), (Processor<T>) new FooProcessor());
map.put((AnInterface<T>) new Bar(), (Processor<T>) new BarProcessor());
}
public List<Person> process(T t, String firstName, String lastName, String id, String cc) {
return map.get(t).process(t, firstName, lastName, id, cc);
}
public static void main(String[] args) {
List<Person> personList = new TestBuilder().process(new Foo(), "John", "Doe", "123", null);
System.out.println(personList);
}
}
The issues I have that I'd like help with are the following:
I am passing null
in some cases in the process
method because not all arguments are relevant for all types. Hence I also want to ask how can I make the approach more flexible i.e. so that I am able (as I add a new type) to pass if possible only the relevant arguments without making the code complicated?