java - 扩展类来存储附加信息是一个好习惯吗?

标签 java swing oop inheritance extends

我想知道扩展在第一时刻创建的类是否是一个好习惯,无需扩展它,只需添加一些您将在以后的应用程序中使用的信息时刻。

例如,我使用 Swing Java API 为我正在开发的应用程序创建 GUI。在构建它时,我需要创建一个 JTable,该模型将根据用户的操作在运行时多次更改。因此,我有三种不同的模型可以根据情况应用于该 JTable。也就是说,在我的应用程序中,我意识到如果我可以扩展 JTable 并创建另一个内部具有 Enum (或任何其他类型)的类,这对我来说会更容易,这可以为我提供 JTable 上处于 Activity 状态的模型就在我检查它的那一刻。所以,我的问题是:扩展 JTable 等只是添加包含可能对应用程序中访问有用的信息的字段是否是一个好习惯?对我来说,直接在 JTable 中保存这些信息并在我有权访问 JTable 时访问它会容易得多。

这是一个好的做法吗?可怕的做法?你的意见是什么?谢谢!

最佳答案

假设 M-V-C 或模型- View -控制程序结构,或相当接近于此的结构,

...create a JTable which model would be changed several times on the runtime depending on what the user did. So, I had like three different models that could be applied to that JTable depending on the situation.

这里的关键是:实际上发生了什么变化? JTable 还是它的 TableModel?如果是 TableModel,我会避免子类化 JTable。

That said, in my application I realized that it would be much more easier to me if I could extend the JTable and create another class which would have a Enum (or any other type) internally which could provide me which model is active on the JTable in the exact moment that I've checked it.

这似乎混淆了 View 和模型。 TableModel 信息应该是程序模型的一部分,如果它发生更改,您可以让模型通知监听器更改。

So, my question is: Is it a good practice to extend, for example, that JTable, just to add fields that have information that will probably be useful to access in the application? For me, it would be a lot easier to hold this information directly in the JTable and access it whenever I have access to JTable.

在这种情况下,我不会继承 JTable 的子类,而是进行重大的状态更改,并且它们的通知将成为主程序模型的一部分,而不是其 View 的一部分(正如您尝试做的那样)。

关于java - 扩展类来存储附加信息是一个好习惯吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26793568/

相关文章:

java - 为什么我收到 HTTP 400 错误请求

java - NoSuchMethodException : org. apache.fop.apps.FopFactory.newInstance()

Java Swing Gridlayout 垂直约束

java - Greasemonkey 脚本使用小程序标签更改 img 标签

java - 跳出循环

java - 如何在 JFrame 的 paint() 函数之外绘制图形

java - Jtable cellEditor 集不适用于我的表模型定义

php - PHP中看似多态的东西真的是多态吗?

actionscript-3 - 为什么不能使用 "final"是一个安全问题?

C++ 错误 "undefined reference to GPScoord::(double,double) etc."