如何避免循环依赖这里 [英] how to avoid circular dependencies here

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

问题描述

有没有办法避免循环依赖,除了混合模块,这样一个安排(这是一个象棋应用程序)

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 a ChessWidget module;
  • ChessWidget just wraps the ChessWorld module and imports CellButton;
  • The CellButton module imports the module Cell;
  • The ChessWorld module imports Board (to represent it) and Players (to notify them and fetch their moves);
  • The Board module imports module Piece;
  • The Piece module imports module Player;

这里是问题:

玩家模块需要了解其他玩家和板,从而导入 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屋!

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