【问题标题】:Handling External Dependencies in a Factory处理工厂的外部依赖
【发布时间】:2010-11-10 03:37:18
【问题描述】:

我有一个我觉得需要重构的工厂类,举个例子:

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 类是一个域对象。工厂类是否应该访问存储库/数据库以获取文件类型?

在这种情况下我应该如何处理依赖关系?

【问题讨论】:

    标签: domain-driven-design factory factory-pattern


    【解决方案1】:

    一种新的、未知的图像文件类型确实不太可能。可以硬编码。

    如果您真的非常想将该文件列表保留为外部依赖项,请将文件类型列表传递给FileFactory 构造函数,并使Create() 成为实例方法而不是静态方法。这将使您保持可测试性和可靠性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-18
      • 1970-01-01
      • 2019-08-13
      • 1970-01-01
      • 1970-01-01
      • 2011-04-05
      相关资源
      最近更新 更多