循环依赖——总是错的?
1.我想知道以下结构是否错误,原因是什么,解决办法是什么: 假设我已经实现了一个网络游戏客户端 客户端有2个主要包:
A.GUI - 持有所有的swing Jpanels等
B.LogicEngine
在逻辑引擎中,我有一个名为 clientThread 的类,其主要目标是与服务器通信以获取要在 Gui 面板上执行的命令,并根据用户在 Gui 面板上的选择结果发送回信息。
2为了做到这一点,我倾向于在 clientThread 中保留主 Gui 面板的引用,反之亦然,在不同项目的两个类之间进行循环引用是否如此错误?
3.在面向对象编程中,从类内部执行要在 Gui 上显示的内容(例如客户端线程,客户端线程负责以某种方式管理游戏流程,尽管它位于逻辑引擎包上)是否是错误的?
4.另外,如果 Gui 部分知道并使用逻辑部分,这是否有问题?
想听听一些建议
非常感谢
1.I would like to know if the following structure is incorrect, what is the reason, and what is the solution for that:
Assume I have implemented a client for net game
The client has 2 main packages:
A.GUI - hold all the swing Jpanels etc.
B.LogicEngine
In Logic engine I have a class called clientThread which main goal is to communicate with the server to get commands to execute on the Gui Panel and also to send information back as a result of the user choices on the Gui Panels..
2.In order to do so I tend to hold reference of my main Gui panel in clientThread and vise versa, is it so wrong to do cyclic reference between two classes of different projects?
3.Is it wrong in matter of object oriented programming to execute things to be shown on the Gui from within class like client thread which is responsible in some way to manage the flow of the game although it is on logical engine package?
4.Also if the Gui part know and uses the logical part is it a problem?
Would like to hear some advices
Thank you very much
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
显然,GUI 应该依赖于引擎,而不是相反(而且,上帝禁止,它们不应该相互依赖)。
您的问题实际上很常见并且很容易解决。引擎线程应该允许客户端代码安装一个侦听器,每次发生事件时都会收到通知。 GUI 实现该侦听器并安装它。请注意,游戏逻辑引擎仅了解侦听器接口,而不了解 GUUI 包中的特定实现。
这是观察者模式的实现,它有几个优点:
最后,从逻辑线程操作 GUI 没有任何问题,但你必须注意 事件调度线程。
Obviously the GUI should depend on the engine, not the other way around (and, god forbid, they should not depend on each other).
Your problem is actually pretty common and simple to solve. The engine thread should allow client code to install a listener that will be notified every time something happens. Than GUI implements that listener and installs it. Note that the game logic engine is only aware of the listener interface, not the particular implementation that lies in your GUUI package.
This is an implementation of the Observer pattern and it has several advantages:
Finally there is nothing wrong with manipulating your GUI from logic thread, hoever you must be aware of event dispatching thread.