我有这样的设计:
public interface IFactory<T> {
T Create();
T CreateWithSensibleDefaults();
}
public class AppleFactory : IFactory<Apple> { ... }
public class BananaFactory : IFactory<Banana> { ... }
// ...
这里虚构的 Apple
和 Banana
不一定共享任何公共类型(当然,除了 object
)。
我不希望客户端必须依赖于特定的工厂,因此,您可以只向 FactoryManager
请求新类型。它有一个 FactoryForType
方法:
IFactory<T> FactoryForType<T>();
现在您可以使用 FactoryForType().Create()
之类的方法调用适当的接口方法。到目前为止,一切都很好。
但在实现层面存在一个问题:如何存储从类型到 IFactory 的映射?天真的答案是 IDictionary>
,但这不起作用,因为 T
上没有类型协变(我正在使用 C# 3.5)。我是否只是坚持使用 IDictionary
并手动进行转换?
I have this design:
public interface IFactory<T> {
T Create();
T CreateWithSensibleDefaults();
}
public class AppleFactory : IFactory<Apple> { ... }
public class BananaFactory : IFactory<Banana> { ... }
// ...
The fictitious Apple
and Banana
here do not necessarily share any common types (other than object
, of course).
I don't want clients to have to depend on specific factories, so instead, you can just ask a FactoryManager
for a new type. It has a FactoryForType
method:
IFactory<T> FactoryForType<T>();
Now you can invoke the appropriate interface methods with something like FactoryForType<Apple>().Create()
. So far, so good.
But there's a problem at the implementation level: how do I store this mapping from types to IFactory<T>
s? The naive answer is an IDictionary<Type, IFactory<T>>
, but that doesn't work since there's no type covariance on the T
(I'm using C# 3.5). Am I just stuck with an IDictionary<Type, object>
and doing the casting manually?
发布评论
评论(1)
不幸的是,是的,您被困在手动铸造中。然而,这种转换可能是一个实现细节,消费者看不到。例如
Unfortunately yes you are stuck with the manual casting. However this casting can be an implementation detail and not seen by the consumer. For example