I have a question about code style:
Let’s assume i have a String containing some information (like “Information1” or “Information2”). Based on this i want to create objects with a factory. Obviously i could write something like this:
if(string.equals("Information1")){
Factory.createInformation1Object();
}
if(string.equals("Information2")){
Factory.createInformation2Object();
}
if(string.equals("Information3")){
Factory.createInformation3Object();
}
Now i was wondering if there is a better (and prettier) way to do this. I really like the multiple dispatch idea of the visitor pattern, but i cant see a way to apply this easily to this particular problem.
You can use the abstract factory pattern.
Create an abstract
Factoryclass [or interface], and classes that extends it:MyObject1Factory,MyObject2Factory, …On preprocessing, populate a
Map<String,Factory>from aStringto the corespondingFactoryinstance, this is done only once in your application.When you need to create a new instance – invoke
map.get(string).create()to create the relevant object, of the relevant type.Edit: Small example with code:
Your classes are:
And your factories will be:
populate a map only once in the program lifetime:
and when you need a new object, invoke with:
(*) Note: The static keyword for classes are here because I created them as inner classes – of course you need to ommit it if it is not your case….