【发布时间】:2014-05-04 11:33:24
【问题描述】:
我有一个通用存储库模式,我现在看到我需要一个自定义方法来实现此模式的一个特定实现,我们将实现称为 CustomerRepository 和方法 GetNextAvailableCustomerNumber。我有一些想法,但它们不符合面向对象设计的 SOLID 原则。
我首先考虑为该实现创建一个自定义存储库模式 (ICustomerRepository),但这并不是很可行。经验告诉我,肯定有其他一些我目前还没有考虑甚至不知道的方法。此外,我不认为为每一个颠簸发明一个新的存储库接口应该做的那么轻松。
然后我考虑让 ICustomerRepository 继承 IRepository
解决这个问题的正确方法是什么?接口继承真的是要走的路,还是有其他理想的符合 LSP 的首选方法?
这是我的通用存储库接口:
public interface IRepository<T>
where T : IEntity
{
T GetById(int id);
IList<T> GetAll();
IEnumerable<T> Query(Func<T, bool> filter);
int Add(T entity);
void Remove(T entity);
void Update(T entity);
}
【问题讨论】:
-
为什么你认为 ICustomerRepository 继承形式 IRepository 违背了 Liskov 的替换原则?
-
"子类型必须可以替代它们的基本类型。"如果向 ICustomerRepository 添加新方法 GetNextAvailableCustomer,它仍然可以被 IRepository 替换。
-
因为 ICustomerRepository 的实现不能替代 IRepository
,因为该实现将具有 GetNextAvailableCustomerNumber 方法。 IRepository 的实现不会有这个。 -
@Maritim 这不是liskovs 的意思。 “程序中的对象应该可以替换为其子类型的实例,而不会改变该程序的正确性”
-
ICustomerRepository 继承 IRepository 而不是其他方式。
标签: c# design-patterns inheritance liskov-substitution-principle