我们有不同类型的图像,我们将图像相应地存储在磁盘上的子文件夹中,并将元数据存储在数据库中,包括 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(但这当然是不可能的。
我能做什么来代替这个?
我会坚持使用枚举的简单解决方案,并使用属性用子目录字符串装饰它,将所有需要的数据放在一个地方:
public enum FileTypes
{
[SubDirectory("documents")]
Document = 1,
[SubDirectory("profilefotos")]
ProfileFoto = 2
}
为了使您的代码更具可扩展性,我认为您需要某种存储所有已知文件类型的注册表。注册表可以是库的一部分并公开,以便外部代码可以注册自己的文件类型。
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);