I am reimplementing a java program in D. I have used the factory pattern, that is, from the data "myclass" "5.3 ,6,8,10", I use reflection to call the construct开发者_StackOverflow中文版or
myclass(5.3 ,6,8,10);
How can I solve the same problem in D, that is, given a class name, and the parameters the constructor takes (only primitives), create an instance of that class by calling the constructor in the parameters?
One obvious solution is the following: Make a huge switch/case statement, with class names as cases, and make constructor take a double[] as argument. This is ugly, since I need to add each new class to this list.
I might enforce each class to statically add themself to some global map, mapping class name to constructor, somehow.
You could have a list with helper objects. The helper objects (MiniFactory) basically have a test method and a factory method, so you can say:
for (int i=0; i<max_classes; i++) {
MiniFactory f = factoryList[i];
if (f.typeIsMatching(inputString))
return f.createObject(inputArgs);
}
With some luck you can use templates to define the MiniFactories.
精彩评论