如何避免循环依赖这里 [英] how to avoid circular dependencies here
问题描述
有没有办法避免循环依赖,除了混合模块,这样一个安排(这是一个象棋应用程序)
Is there a way to avoid circular dependencies, other than mixing modules, in a arrangement like this(it is a chess application)
长描述:
- 有
Gui
模块导入ChessWidget
module; -
ChessWidget
只包裹ChessWorld
模块和导入
CellButton
; -
CellButton
导入模块单元格
; -
ChessWorld
模块导入董事会
(代表它)和玩家
(通知他们并取得他们的举动); -
董事会
模块导入模块Piece
; -
Piece
模块导入模块玩家
;
- There is the
Gui
module which imports aChessWidget
module; ChessWidget
just wraps theChessWorld
module and importsCellButton
;- The
CellButton
module imports the moduleCell
; - The
ChessWorld
module importsBoard
(to represent it) andPlayers
(to notify them and fetch their moves); - The
Board
module imports modulePiece
; - The
Piece
module imports modulePlayer
;
这里是问题:
玩家
模块需要了解其他玩家和板,从而导入 ChessWorld
!
The Player
module needs to know about other players and the board, thus importing ChessWorld
!
简短描述
世界
模块需要知道 Player
模块(甚至间接地由 Board
/ Piece
)和玩家
需要了解世界
。
The World
module needs to know about the Player
module (even indirectly by Board
/Piece
) and Player
need to know about World
.
帮助非常感谢。
PS:不是因为我不能使用循环依赖因为他们是邪恶的。
PS: Is not because I cant use circular dependencies, but because they are evil.
推荐答案
按照依赖性反转原则:引入一个界面,其中 ChessWorld
实现,而 Player
依赖 - 和/或一个 Player
实现,而 Piece
取决于(或者两者都可能是根据依赖性质的细节而定)。这通常与依赖注入相结合,如果依赖者需要动态实例化一些实例的受资人,工厂 DP。
Follow the Dependency inversion principle: introduce an interface, which ChessWorld
implements, and on which Player
depends -- and/or one which Player
implements and on which Piece
depends (either or both may be appropriate depending on details on the nature of the dependency). This often goes together with Dependency Injection, and, if the dependant needs to dynamically instantiate a number of instance of the dependees, with Factory DPs.
这篇关于如何避免循环依赖这里的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!