接口由Moq用于生成模拟对象进行单元测试.但这是接口重新使用的唯一时间.
我们系统中没有具体对象实现多个接口.
有谁能告诉我这是否会导致问题呢?如果是这样,他们会是什么?
我在想,我们的应用程序有很多重复,例如在这两个接口(在我们的服务层中编辑):唯一不同的是方法名和参数的类型,但语义上它们是与他们发送消息的存储库相同的事情:
- interface ICustomer
- {
- void AddCustomer(Customer toAdd);
- void UpdateCustomer(Customer toUpdate);
- Customer GetById(int customerId);
- }
- interface IEmployee
- {
- void AddEmployee(Employee toBeAdded);
- void UpdateEmployee(Employee toUpdate);
- Employee GetById(int employeeId);
- }
这就是我认为重用抽象原则会进入的地方,即将代码转换成如下代码:
- public interface IEmployee: IAdd<Employee>,IUpdate<Employee>,IFinder<Employee>
这不是关于存储库模式 – 这是关于任何层中的接口,看起来像它们共享语义相同的行为.是否值得为这些操作导出通用接口,并使“子接口”从它们继承?
至少它会保持方法的签名一致.但这会给我什么其他好处? (Liskov替代原则)
解决方法
- public interface IRepository<TEntity> where TEntity : IEntity
- {
- T FindById(string Id);
- T Create(T t);
- bool Update(T t);
- bool Delete(T t);
- }
- public interface IEntity
- {
- string Id { get; set; }
- }
编辑
No concrete objects in our system implement multiple interfaces.
Can anyone tell me if this is going to cause problems down the road?
And if so,what would they be?
是的,如果还没有开始这样做会造成问题.
你会得到一堆不会为你的解决方案添加的接口,在维护和创建它们的时候耗尽了很大一部分时间.随着你的代码库的大小增加,你会发现并不是一切都像你曾经想过的一样
请记住,接口只是一种工具,是实现抽象级别的工具.而抽象是一个概念,一个模式,一个独立实体共享的原型.
你总结了这个,
This isn’t about the repository pattern – this is about interfaces in any layer that look like they share semantically identical behavIoUrs. Is it worth deriving common interfaces for these operations and making “sub-interfaces” inherit from them?
这不是关于接口,这是关于抽象的,Repository模式演示了如何抽象出针对特定对象定制的行为.
上面给出的示例没有任何名为AddEmployee或UpdateEmployee的方法…这样的方法只是浅层接口,而不是抽象.
存储库模式的概念是显而易见的,因为它定义了一组行为,这些行为由多个不同的类实现,每个类针对特定实体进行定制.
考虑到为每个实体(UserRepository,BlogRepository等)实现Repository,并且考虑到每个存储库必须支持核心功能集(基本CRUD操作),我们可以采用该核心功能集并在界面中定义它,然后在每个Repository中实现这个界面.
现在我们可以从我们从Repository模式中学到的东西,并将其应用到我们应用程序的其他部分,从而定义一个新的接口中的一些对象所共享的核心行为,然后从接口.
- public interface IVehicleOperator<TVehicle> where TVehicle : IVehicle
- {
- void Accelerate();
- void Brake();
- }
在这样做的时候,我们不再有1:1的映射,而是一个实际的抽象.
在我们讨论这个话题的时候,也许值得一看的是装饰图案.