I have a (growing) list of Data-Generators. The generator I need is created by the factory class. Generators implement a common interface, which includes, among other things, a static name string.
What I would like to do: Call the factory.Create method with a string parameter for the specified name. The create method finds a generator with this name and returns a new instance of the specified generator.
A bonus, in my opinion, is for this: I only need to add new generator classes without having to edit the factory.
Question:
- Is this a good way to deal with this problem?
- How can I find all the generators? Reflection on each implementation of the interface / each member of the namespace (unique to generators + their interface)?
- Is this the right way to name the factory, or is it some other template?
In the end, I would call factory as follows (simplified):
//Caller public DataModel GetData2() { var generator = new DataFactory().Create("Gen.2"); return generator.GetData(); } //Factory public class DataFactory { public AbstractDataGenerator Create(string type) { //Here the magic happens to find all implementations of IDataGenerator var allGenerators = GetImplementations(); var generator = allGenerators.FirstOrDefault(f => f.name == type); if (generator != null) return (AbstractDataGenerator)Activator.CreateInstance(generator); else return null; } } //Interface public abstract class AbstractDataGenerator { public static string name; public abstract DataModel GetData(); } //Data-Generators public class DataGen1 : AbstractDataGenerator { public static string name = "Gen.1"; public DataModel GetData() { return new DataModel("1"); } } public class DataGen2 : AbstractDataGenerator { public static string name = "Gen.2"; public DataModel GetData() { return new DataModel("2"); } }
Should the magic of GetImplementations() in the factory be done through Reflection or something else? Should I use a completely different approach?
Since the answers relate to IoC and DI: this project already uses NInject, so it will be available. Switched from interface to abstract class.
c # design-patterns factory
MilConDoin
source share