处理循环依赖
我想知道是否有人可以提出任何好方法来打破 Java 中两个类之间的循环依赖关系。FindBugs 建议使用接口,所以我想知道是否有人对此类问题有任何好的经验。
I wonder if someone can advise on any good ways to break a circular dependency between 2 classes in Java.FindBugs proposes the use of interfaces so i wonder if someone has any good experience with this type of problem.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
循环依赖并不总是需要避免的。我会避免将它们放在大的地方,但保留在系统的小角落里。从大的角度来看,即如果 J2EE 应用程序的数据访问层和表示层循环依赖,我会说这是一件坏事,因为这意味着所有内容都必须一次性编译,而测试是一场噩梦。但是,如果列表数据结构及其迭代器类型是循环依赖的,则没有问题。
正如 Findbugs 建议使用接口来打破循环依赖。即为至少一种类型的圆引入一个接口,并让其他类在任何地方都使用该接口。您需要示例代码吗?
Circular dependencies aren't always to be avoided. I'd avoid them in the large, but keeps in small tight corners of a system. In the large, i.e if data access layer and the representation layer of J2EE app circular dependent, I'd say that is a bad thing, because it means that everything has to be compiled in one go and testing is nightmare. But, it's no problem if a list data-structure and its iterator type are circular dependend.
As Findbugs suggests use interfaces to break a circular dependency. I.e introduce a interface for at least one type of the circle and make the other classes use the interface everywhere. Do you need example code?
建议阅读有关依赖倒置原则的内容,例如 什么是依赖倒置原则,为什么它很重要? 或 http://en.wikipedia。 org/wiki/Dependency_inversion_principle
Suggest reading about the dependency inversion principle, e.g. What is the Dependency Inversion Principle and why is it important? or http://en.wikipedia.org/wiki/Dependency_inversion_principle
有一篇博客文章 此处了解如何使用 Restruction101 从 Junit 和
至于关于循环依赖是否不好的争论,我建议阅读Uncle Bob的Solidprinciples。
免责声明:我在 Headway Software 工作,该公司是 Restruction101 的开发人员。
There's a blog post here on how Restructure101 was used to remove cyclic dependencies, "tangles", from Junit and a presentation from the Lausanne JUG on how it was used to remove tangles from Icefaces.
As for the debate on whether cyclic dependencies are bad, I suggest reading Uncle Bob's Solid Principles.
Disclaimer: I work for Headway Software the developers of Restructure101.