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 - 使用 Set - 自动删除重复项?

Java Dice Game - 根据掷骰子和轮流选择谁开始游戏

java - 如何在 Java Swing 应用程序中管理来自 Controller 的 View 更新

php - 如何在其他类中使用PDO连接?

java - HashMap 中的重复值

java - JPanel 由 textFields 组成

基于 Java 的 Swing 浏览器应该支持 JavaScript

java - 更新 JFrame 中的 JPanel

java - 为什么 Serialized 被称为接口(interface)?

linq - Linq 在 .NET OOP/D 中最强大且意想不到的好处是什么?