gpt4 book ai didi

c# - 存储库模式是否遵循 SOLID 原则?

转载 作者:可可西里 更新时间:2023-11-01 07:50:38 26 4
gpt4 key购买 nike

我正在对 SOLID principal 进行一些研究,发现了 Repository 模式实现中的一些问题。我将逐一解释,如有错误请指正。

问题 1

存储库模式打破了单一职责原则 (S)

假设我们有一个定义为

的接口(interface)
public interface IRepository<T> where T: IEntity
{
IEnumerable<T> List { get; }
void Add(T entity);
void Delete(T entity);
void Update(T entity);
T FindById(int Id);
}

显然它违反了单一责任原则,因为当我们实现这个接口(interface)时,在一个类中我们同时放置了 Command 和 Query。这不是预期的。

问题 2

存储库模式打破接口(interface)隔离原则(I)

假设我们有 2 个上述接口(interface)的实现。

第一次实现

CustomerRepository : IRepository<Customer>
{
//All Implementation
}

第二次实现

ProductRepository : IRepository<Product>
{
//All Implementation except Delete Method. So Delete Method Will be
void Delete (Product product){
throw Not Implement Exception!
}
}

根据 ISP,“不应强制客户端依赖于它不使用的方法。”所以我们清楚地看到它也违反了ISP。

所以,我的理解是 Repository 模式不遵循 SOLID 原则。你怎么看?为什么要选择这种违背Principal的模式呢?需要你的意见。

最佳答案

Clearly it violates the single responsibility principle because when we implement this interface, In a single class we are putting Command and Query both. and this not expected.

这不是单一职责原则的意思。 SRP 意味着该类应该一个主要关注点。存储库的主要关注点是“使用类似集合的接口(interface)来访问域对象,在域和数据映射层之间进行调解”(Fowler ).这就是这个类所做的。

Repository Pattern Breaks Interface segregation principle

如果这让您感到困扰,那么只需提供另一个不包含您不打算实现的方法的接口(interface)。不过,我个人不会那样做;它是为了边际利益而提供的许多额外接口(interface),并且不必要地使 API 困惑。 NotImplementedException 非常不言自明。

您会发现计算中有很多规则、法律或原则都有异常(exception),有些甚至是完全错误的。拥抱歧义,学习从更实际的角度编写软件,并停止以这种绝对的方式思考软件设计。

关于c# - 存储库模式是否遵循 SOLID 原则?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28102970/

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