Reputation: 999
I would like to create a factory, but it's not simple with Spring and again I'm lost in space :p
This is what i would like to do.
I have an abstract class which implements multiple interface (Runnable and some personal interfaces)
public abstract class AbstractDocMan implements Runnable, DocMan {
protected AbstractDocUnit docUnit;
// some attributes
// some getter & setter
}
I have some classes which extends from this abstract class, i will call them : W, S & E :p And some classes for the Abstract attribute (docUnit) called : WD for W, SD for S and ED for E :)
Now considering a parameter, i would like to instantiate the good class in my main controller. I would like a generic code, but working with specific class considering the good process.
Something like that.
@Component("mainVm")
@Scope("prototype")
public class MainVm {
@Autowired
private DocManFactory docManFactory;
// ???
private AbstractDocMan docMan;
...
public void setProcess(String myProcess) {
docMan = docManFactory.getDocMan(myProcess);
}
}
For moment, i have a factory defined strangely. It is working but i don't think it's a good practice :
public class DocManFactory {
@Autowired
private S s;
@Autowired
private W w;
@Autowired
private E e;
@Autowired
private SD sd;
@Autowired
private WD wd;
@Autowired
private ED ed;
public AbstractDocMan getDocMan(String myProcess) {
AbstractDocMan adm = null;
if ("S".equals(myProcess)) {
s.setDocUnit(sd);
adm = s;
} else if ("W".equals(myProcess)) {
w.setDocUnit(wd);
adm = w;
} else if ("E".equals(myProcess)) {
e.setDocUnit(ed);
adm = e;
}
return adm;
}
}
So my questions : - How to inject dynamically the good docUnit in the factory ? cause here all object are instantiate (s,e,w,sd,ed,wd) zzz - Is there a way to annotate the attribute in main controller ?
So...How to do a good factory with Spring (v3.1.1).
Thank you.
Upvotes: 1
Views: 441
Reputation: 308763
I think generics and a Map are the solutions here.
Your instinct is correct: this implementation is far too brittle. Start with this:
public DocManFactory {
// You can inject or hard wire these
private static final Map<String, AbstractDocMan> INSTANCES;
public static AbstractDocMan getDocMan(String processName, Process process) {
AbstractDocMan docMan = INSTANCES.get(processName);
process.setDocUnit(docMan);
return docMan;
}
}
Generics can help if the Process
class that I assumed varies.
Upvotes: 1