我有一个我觉得需要重新考虑的工厂类,请看下面的例子:
public class FileFactory
{
public static FileType Create(string fileName)
{
if(IsImageFile(fileName))
{
return new ImageFileType();
}
else if(IsDocumentFile(fileName))
{
return new DocumentFileType();
}
...
}
private static bool IsImageFile(string fileName)
{
string imageFileTypes[] = string[] {".jpg", ".gif", ".png"}; //How to avoid this line of code?
return imageFileTypes.Contains(fileName);
}
}
我松散地遵循域驱动设计原则,因此这个FileFactory类是一个域对象。工厂类是否应该访问存储库/ DB以获取文件类型?
我应该如何处理这种情况下的依赖?
答案 0 :(得分:0)
新的未知图像文件类型确实不太可能。对此进行硬编码很好。
如果您真的非常希望将该文件列表保留为外部依赖项,请将文件类型列表传递到FileFactory
构造函数中,并使Create()
成为实例方法而不是静态方法。这将让你保持可测试和坚固。