循环依赖是好是坏 [英] Is circular dependency good or bad

查看:69
本文介绍了循环依赖是好是坏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要知道为什么我们需要避免循环依赖?
如果在我们的现实世界中,循环依赖非常重要。就像一个朋友需要其他朋友提供的东西,而另一个朋友也需要该朋友提供的东西一样,所以这种通知是正确的吗?
如果真的需要避免这种情况,那么在面向对象的世界中针对这种情况的最佳设计是什么?

解决方案

具有循环依赖关系的问题就像鸡肉和鸡蛋问题。



如果您依赖我设置某些东西,而我又依赖您设置一些东西,那么我们开始吗?



其必然结果是如何结束-如果我引用了您的资源,而您引用了我的资源,我将永远无法清理,因为那样会破坏



在两种情况下,答案都是引入一个中间人,将一方的依赖关系转移给他,因此,如果您将资源传递给中间人,则将取决于我和中间人,而我将取决于中间人。因此,您可以清理,因为您现在不拥有任何资源,而我可以清理,因为没有人依靠我,然后中间人就可以清理。


I need to know why we need to avoid circular dependencies? In the real world if we think, circular dependencies are pretty much important. Like one friend needs something from other friend and the other needs something from this friend, so its kind of circular right?

Then why is circular dependency a bad design? If we really need to avoid this then what is the best possible design in Object oriented world for such a situation?

解决方案

The problem with circular dependencies is rather like the chicken and egg problem.

If you depend on me setting something up, and I depend on you setting something up, how do we start?

The corollary of this is how do we end - if I have a reference to your resource and you have a reference to mine, I can never clean up because that would break you, and you cannot clean up because that would break me.

The answer in both cases is to introduce a middleman, passing the dependency from one of the parties to him, So if you passed your resource on to the middleman, you would depend on me and the middleman, and I would depend on the middleman. Thus you can clean up because you now hold no resource, and I can clean up because no-one depends on me, and then the middleman can clean up.

这篇关于循环依赖是好是坏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆