Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
626 views
in Technique[技术] by (71.8m points)

design patterns - 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)

Long description:

  • 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;

AND HERE IS THE PROBLEM:

The Player module needs to know about other players and the board, thus importing ChessWorld!

Short description:

The World module needs to know about the Player module (even indirectly by Board/Piece) and Player need to know about World.

Help is very appreciated.

PS: Is not because I cant use circular dependencies, but because they are evil.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...