How can I make this simple C # generics factory work?

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?

+4
source share
1 answer

Unfortunately, you are stuck in manual casting. However, this casting can be a detail of the implementation and is not visible to the consumer. for instance

 public class FactoryMap { private Dictionary<Type,object> _map = new Dictionary<Type,object>(); public void Add<T>(IFactory<T> factory) { _map[typeof(T)] = factory; } public IFactory<T> Get<T>() { return (IFactory<T>)_map[typeof(T)]; } } 
+5
source

Source: https://habr.com/ru/post/1310261/


All Articles