代码之家  ›  专栏  ›  技术社区  ›  barii

按id列出的接口实例

  •  -1
  • barii  · 技术社区  · 7 年前

    我们有不同类型的图像,我们将图像存储在磁盘上相应的子文件夹中,并将元数据存储在数据库中,包括fileTypeId。 目前我们有:

    public enum FileTypes
    {
        Document=1,
        ProfileProto
        ...
    }
    

    switch (fileType)
       case 1:
            subdir = "documants"
       case 2:
            subdir = "profilephotos
       default: ...error...
    

    像这样的

    这违反了SOLID的打开/关闭原则

    因此,我尝试创建以下内容:

    public class DocumentFileType : IFileType
    {
        public int Id => 1;
        public string Subfolder => "documents";
    }
    

    但问题是,当我们将图像的元数据存储到数据库中时,我们将类型的id存储到数据库字段中。在这种情况下为1或2。 所以当我检索时,我应该 IFileType fileType=IFileType。instnceWithId(1) 但这当然是不可能的。

    我能做什么来代替这个?

    2 回复  |  直到 7 年前
        1
  •  0
  •   doerig    7 年前

    我会坚持使用带有枚举的简单解决方案,并使用一个属性用子目录字符串来修饰它,以便将所有需要的数据放在一个地方:

    public enum FileTypes
    {
        [SubDirectory("documents")]
        Document = 1,
    
        [SubDirectory("profilefotos")]
        ProfileFoto = 2 
    }
    
        2
  •  0
  •   doerig    7 年前

    为了使代码更具可扩展性,我认为您需要某种注册表来存储所有已知的文件类型。注册表可以是库的一部分并公开,以便外部代码可以注册自己的文件类型。

    public class DocumentFileTypeRegistry 
    {
        IDictionary<int, IFileType> _registeredFileTypes = new Dictionary<int, IFileType>();
    
        public void RegisterType(IFileType type)
        {
            _registeredFileTypes[type.Id] = type;
        }
    
        public IFileType GetTypeById(int id)
        {
            return _registeredFileTypes[id];
        }
    }
    
    public class DocumentFileType : IFileType
    {
        public int Id => 1;
        public string Subfolder => "documents";
    }
    
    public class PhotoFileType : IFileType
    {
        public int Id => 2;
        public string Subfolder => "photos";
    }
    

    然后您必须在注册表中注册文件类型:

    _fileTypeRegistry = new DocumentFileTypeRegistry();
    _fileTypeRegistry.RegisterType(new DocumentFileType());
    _fileTypeRegistry.RegisterType(new PhotoFileType());
    
    //retrieve the type by id
    var fileType = _fileTypeRegistry.GetTypeById(1);