I have this construct:
public interface IFactory<T> { T Create(); T CreateWithSensibleDefaults(); } public class AppleFactory : IFactory<Apple> { ... } public class BananaFactory : IFactory<Banana> { ... }
Fictitious Apple and Banana here do not necessarily have common types (except for object , of course).
I donβt want customers to depend on specific factories, so instead you can just ask FactoryManager for a new type. It has a FactoryForType method:
IFactory<T> FactoryForType<T>();
Now you can call the appropriate interface methods with something like FactoryForType<Apple>().Create() . So far so good.
But there is a problem at the implementation level: how to keep this mapping from types to IFactory<T> s? The naive answer is IDictionary<Type, IFactory<T>> , but this does not work, since there is no type covariance on T (I use C # 3.5). Am I just stuck with IDictionary<Type, object> and do manual casting?
source share