应该如何设计以数据库为中心的 Java Swing 应用程序?
我编写一个以数据库为中心的 Java Swing 应用程序已经有一段时间了。
GUI 和 DAO 代码最终形成一棵大树,如下所示:
JFrame
|
JTabbedPane
|
+--------------------+----------------------+-------------+
| | | |
JPanel1 JPanel2 JPanel3 JPanel4
| | | |
JButtons--JTable1 JTextFields--JButton JTable2 JDialog--JTable3
i! i! i! i!
Model1 Model2 Model3 Model4
| | | |
+------------+-----------+---------+-------------------+
|
DataAccessObject
应用程序有多个视图,有些包含用于显示数据的 JTable,有些包含带有用于编辑或添加数据的表单的对话框。
我有一个带有 JDBC 连接的 DataAccessObject
。我使用多个模型(扩展 AbstractTableModel
)将视图(表单或表)与 DAO 连接起来。
在我的第一个版本中,我将 DAO 实现为单例,然后我了解到这是一种反模式,并使用依赖注入来代替,所以我基本上首先初始化 DAO,然后将其注入到所有模型的构造函数中。然后我初始化 JFrame 并在 GUI 树的构造函数中注入对模型的引用。
通过洞 GUI 树传递对模型的引用感觉非常笨拙,但我知道我可以很好地控制依赖关系。但是,是否有更好的设计可以用于以数据库为中心的 Java Swing 应用程序,该应用程序具有许多数据视图,需要一个与数据库连接的模型?
I have been writing a database-centric Java Swing application for a while.
The GUI and DAO-code ends up in a big tree like:
JFrame
|
JTabbedPane
|
+--------------------+----------------------+-------------+
| | | |
JPanel1 JPanel2 JPanel3 JPanel4
| | | |
JButtons--JTable1 JTextFields--JButton JTable2 JDialog--JTable3
i! i! i! i!
Model1 Model2 Model3 Model4
| | | |
+------------+-----------+---------+-------------------+
|
DataAccessObject
The application has several views, some contains a JTable for showing data, and some contain a dialog with a form for editing or adding data.
I have a DataAccessObject
with JDBC-connection. I use several models (extends AbstractTableModel
) to connect the views (forms or tables) with the DAO.
In my first version I implemented the DAO as a Singleton, then I learned that this is an anti-pattern and used Dependency Injection instead, so I basically initialize the DAO first and then inject it to the constructor of all the models. Then I initialize the JFrame and inject a reference to the models in the constructor in the hole GUI-tree.
Passing the reference to the models through the hole GUI tree feels very clumsy, but I know that I have good control of dependencies. But is there any better design I could use for a database-centric Java Swing applications with many views of data that needs a model with a connection to the database?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我也支持 Shakedown 的评论。这都是关于层的。将您的代码分成层/层。
既然您谈论的是依赖注入,我建议您看一下 Spring Rich Client 框架,以了解如何设计/开发优秀的 Swing 应用程序。
I would also support Shakedown's comment. It is all about layers. Separate your code into layers/tiers.
Since you were talking about Dependency Injection I would suggest you to take a look at Spring Rich Client framework to get a feel about how good Swing applications can be designed/developed.