gpt4 book ai didi

design-patterns - 什么属于存储库,什么不属于?

转载 作者:行者123 更新时间:2023-12-04 15:05:30 25 4
gpt4 key购买 nike

在实现存储库模式的 ASP.NET MVC 应用程序中,我很好奇如果它们仍然与给定存储库的一般焦点相关,是否适合将非数据相关方法放置在存储库中。例如,假设 ProductsRepository 具有添加和删除 ProductImages 的方法,这些方法在数据库和本地文件存储中也有部分表示。如果需要删除 ProductImage,我们需要使用存储库方法从数据库中删除一行,还需要从存储介质中删除与该图像关联的文件。 IO 操作是否属于存储库,还是有更合适的位置?

在我刚才描述的情况下,我一直在做的一件事是在我的存储库中提供静态方法,这些方法通过使用存储在数据库中的文件名和预定义的目录模式以编程方式生成它,为我提供给定 ProductImage 的路径.这超出了存储库的预期用途吗?

编辑

如果这样的操作不属于存储库,那么在 MVC 模式中应该去哪里?在我看来,在 Controller 和 Repository 之间有另一个层可能是有意义的,它根据需要调用 Repository 并且可以从 Controller 静态调用。

最佳答案

我认为对存储库模式的更大担忧是您违反了单一责任原则。你的类应该有一个职责,比如操作数据库中的数据。您应该有一个不同的类来处理文件 IO,并且您可以将一个类中的函数向上分组。

更改一个类应该只有一个原因,而处理文件 IO 和 db 调用的存储库类将有两个。更改文件系统布局或更改数据库。

编辑

为了解决您的编辑问题,这是我将如何在 MVC 场景中实现它(这也假设您正在使用某种依赖注入(inject)来使生活更轻松)。

// Controller class
public class ProductsController
{
private IProductService _productService;

public ProductsController(IProductService productService)
{
_productService = productService
}

public void RemoveImage(int productId, int imageId)
{
_productService.RemoveImage(productId, imageId)
}
}

public class ProductService: IProductService
{
private IProductRepository _productRepository;
private IProductImageManager _imageManager;

public ProductService(IProductRepository productRepository, IProductImageManager imageManager)
{
_productRepository = productRepository;
_imageManager = imageManager;
}

public void RemoveImage(int productId, int imageId)
{
// assume some details about locating the image are in the data store
var details = _productRepository.GetProductImageDetails(productId, imageId);
// TODO: error handling, when not found?
_imageManager.DeleteImage(details.location);
_productRepository.DeleteImage(productId, imageId)
}
}

然后,您可以根据任何接口(interface)来实现 IProductImageManager 和 IProductRepository,这些接口(interface)对于您的特定需求的具体实现是有意义的。

关于design-patterns - 什么属于存储库,什么不属于?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1300773/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com