I am using DI to pass around my dependencies. But in some scenarios we need to create objects dynamically and do need to provide parameters during initialization. Code sample -a tries to explain the scenario.
In order to initialize such type of objects and hide new operator, I created simple factories. Code sample -b.
Code sample -a
int are used for simplicity they will/can actually be some real objects
public class Sample {
private final int c;
public Sample(int c){
this.c = c;
}
public void doSomething(SomeCommand command, Request request, Context context){
DynamicDependency dynamicDependency = new DynamicDependency(command.getA(), command.getB(), c);
dynamicDependency.doSomeWork(request, context);
}
}
class DynamicDependency{
private final int a;
private final int b;
private final int c;
public DynamicDependency(int a, int b, int c){
this.a = a;
this.b = b;
this.c = c;
}
public void doSomeWork(Request request, Context context){
/*
Do work
*/
}
}
class SomeCommand {
private int a;
private int b;
public int getA() {
return a;
}
public void setA(int a) {
this.a = a;
}
public int getB() {
return b;
}
public void setB(int b) {
this.b = b;
}
}
Code sample -b
public interface IParameterizedObjectFactory<T> {
T getInstance(Object... arguments) throws ClassCastException;
}
public class DynamicDependency implements IParameterizedObjectFactory<DynamicDependency> {
@Override
public DynamicDependencyFactory getInstance(Object... arguments) throws ClassCastException {
Validate.notNull(arguments);
if(arguments.length > 0){
final int a = (Integer) arguments[0];
final int b = (Integer) arguments[1];
final int c = (Integer) arguments[2];
return new DynamicDependency(a, b,c);
}
return null;
}
}
This does the job as I can now inject factory and then use it to get the new object as:
DynamicDependency dynamicDependency = dynamicDependencyFactory.getInstance(a,b,c);
Question(s):
Though, it does the job but we need to pass around list of Object[s] and and we loose strong typing. Casting also will eat up some execution time. How can it be improved?
Another approach could be to not to use the interface at all and use concrete classes which have getInstance method with appropriate parameter list. Sounds reasonable to me.
public class DynamicDependencyFactory {
public DynamicDependency getInstance(int a, int b, int c) {
return new DynamicDependency(a, b,c);
}
}
What else can be done to hide new? Or should I use second approach to create concrete factories?
Note: I am trying to stay away from reflection