简体   繁体   English

接口层次结构

[英]Hierarchy of interfaces

Is it considered bad to create a hierarchy of interfaces in Java? 用Java创建接口层次结构是否被认为不好?

I have designed my repository layer like this: 我已经这样设计我的存储库层:

  • Repository , contains CRUD methods Repository ,包含CRUD方法
  • JPARepository , potential methods that is only needed in JPA JPARepository ,仅在JPA中需要的潜在方法
  • SomeModelRepository , specific methods for the repository of that model. SomeModelRepository ,该模型的存储库的特定方法。
  • SomeModelJPARepository , extends JPARepository AND SomeModelRepository SomeModelJPARepository ,扩展JPARepository和SomeModelRepository

Is this considered bad practice, and is it a strange organized hierarchy? 这被认为是不好的做法吗?它是一个奇怪的有组织的等级制度吗?

No, in fact it's fairly common to create interface hierarchies, at least in libraries. 不,实际上,至少在库中创建接口层次结构是相当普遍的。 Take NavigableSet for instance, which has 4 layers of interfaces above it (SortedSet, Set, Collection, Iterable). NavigableSet为例,它上面有4层接口(SortedSet,Set,Collection,Iterable)。

In this example, the diamond inheritance is a bit peculiar, but if necessary not a bad choice per se. 在此示例中,钻石继承有点特殊,但是如果需要的话,这本身并不是一个坏选择。 But usually a tree hierarchy is much clearer and better. 但是通常,树的层次结构更加清晰,更好。 In this case I would consider making either: 在这种情况下,我将考虑进行以下任一操作:

  1. SomeModelRepository a subclass of JPARepository, thus forcing all implementing classes to support JPA SomeModelRepository是JPARepository的子类,因此强制所有实现类都支持JPA
  2. Specifying the JPA support in a different interface, not a subclass from Repository. 在不同的接口而不是Repository的子类中指定JPA支持。 Then all classes could choose whether to implement JPA independent of their specific Repository interface. 然后,所有类都可以选择是否独立于其特定的Repository接口来实现JPA。 See Serializable for an example. 有关示例,请参见可序列化 This is the de facto solution for signalling that a class supports a specific feature like "serialization", or maybe "persistence" like in this case. 这是用于发出信号的类的事实解决方案,该类支持某种特定功能,例如“序列化”或“持久性”(在这种情况下)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM