4

Is it a good OOD practice to have a class that has a reference to another class(Composition) which inturn has a reference to the same class?

ClassA ----->ClassB and ClassB ----->ClassA ??

By having this sort of relationship, I can make changes to the states of object class A from B and vice versa. Is this a good design pattern to establish communication between objects or is there a different preferred approach to this??

4

1 回答 1

4

这种关系是循环依赖。就其本身而言,它只有缺点。它可以阻止许多垃圾收集器死在他们的轨道上。释放对象需要 A 和 B 的客户端之间进行协商,因为 A 的所有客户端本质上也是 B 的客户端,反之亦然。

鉴于这种相互依赖关系,您可能应该引入另一个管理相互依赖对象集合的对象。客户都可以和经理协商,决定什么时候完成,什么时候可以释放资源。

为避免此问题,请在上下文中将对象的引用作为函数参数(或类似的瞬态、本地状态)传递,而不是使用持久成员。

于 2013-07-09T03:40:18.187 回答