我正在开发一个需要严格解耦接口的模块。具体来说,在实例化根对象(数据源)之后,用户只应该通过接口与对象模型进行交互。我有实际的工厂对象(我称它们为提供者)来提供实现这些接口的实例,但这留下了获取提供者的笨拙。为此,我在数据源上提供了几个方法:
public class MyDataSource
{
private Dictionary<Type, Type> providerInterfaceMapping = new Dictionary<Type, Type>()
{
{ typeof(IFooProvider), typeof(FooProvider) },
{ typeof(IBarProvider), typeof(BarProvider) },
// And so forth
};
public TProviderInterface GetProvider<TProviderInterface>()
{
try
{
Type impl = providerInterfaceMapping[typeof(TProviderInterface)];
var inst = Activator.CreateInstance(impl);
return (TProviderInterface)inst;
}
catch(KeyNotFoundException ex)
{
throw new NotSupportedException("The requested interface could not be provided.", ex);
}
}
}
我已经动态修改了一些细节以简化(例如,这个代码片段不包括传递给创建的实现实例的参数)。这是在 C# 中实现工厂方法的一种很好的通用方法吗?