继承 JFrame 违反泛化

Inheriting JFrame violates Generalization

在开发 java 独立应用程序时,一些开发人员倾向于扩展 JFrame class 和实现(实现)一些 actionlistener 接口。是不是违反了oops中的泛化概念,也违反了抽象。是不是也违反了单一职责原则。

[编辑] 通过违反 oops 中的泛化概念,我的意思是 "is-a" 关系变得无效。 继承一个class改为扩展一个class

您的问题有点令人费解且难以理解,因为您使用了奇怪的术语。这些句子是正确的并且有意义:

  • a class 扩展另一个 class
  • a class 实现一个接口
  • a class 从其父 class
  • 继承方法

这些句子不合适,不清楚:

  • 一个class继承另一个class
  • 违反泛化概念

尤其是没有代码,我只能猜到你在问什么,但我还是尽量回答:

  • a class 扩展了 JFrame 并同时实现了一个动作侦听器接口,违反了单一职责原则,因为它同时是 2 个东西
  • a class 扩展 JFrame,同时包含一些与显示或配置 JFrame 无关的逻辑,同时做 2 件事违反了单一职责原则。它还违反了模型-视图-控制器的良好分离
  • a class 扩展了 JFrame,但就其行为/实现而言,它主要不是 JFrame 而是其他东西,那么它违反了 JFrame 的抽象,它不应该扩展 JFrame 但可能改为包含它

这种常见的反模式带来了几个问题:

class Application extends JFrame implements ActionListener {}
  • 给定一个 preference for composition over inheritance,一个 Application 可能 有一个 JFrame,但它应该只有 扩展 JFrame 以覆盖其现有功能。

  • 以这种方式实现接口会导致 leaking this in a constructor. This compounds the problem of ensuring that Swing GUI objects are constructed and manipulated only on the event dispatch thread.

  • 关于generalization, a JFrame is a specialization of Window, used as a top-level container. Don't confuse the containment hierarchy with the class hierarchy

  • 关于 single responsibility, the JFrame API shows a coherent derivation, despite Swing's history and cross-platform 抽象。

实现一个控制接口,例如ActionListener,对于self-contained example, but a complex application will likely need more than one controller. An example using is examined here. See also Why CS teachers should stop teaching Java applets

可能会很方便