We are being provided a set of Entity and Consumer classes. Calling the XConsumer returns an XEntity, while calling the YConsumer returns an YEntity and so on. The APIs for the Consumer classes are identical taking arguments of same type. However, the Consumer and Entity classes do not inherit from a base class nor implement an Interface. What I would like to achieve is to generically call a factory that returns a desired Entity of a particular type. My current implementation looks like so:
static class Factory<TConsumer> where TConsumer : new()
{
static dynamic Consume(Document document, out List<Error> errors)
{
// Common code before calling any consumer goes here
Stream stream = document.Stream;
dynamic consumer = Activator.CreateInstance(typeof(TConsumer));
return consumer.Consume(stream, out errors);
}
}
My calling code looks like so
XEntity entity = Factory<XConsumer>.Consume(document, out errors);
Note I’m only in charge of the Factory class and the calling code and not allowed to modify the Entity and Consumer classed. Is there a way to make this better, preferably without using dynamic and reflection or is this as good as it gets?
Aucun commentaire:
Enregistrer un commentaire