使用 Java 中的接口作为与更多团队一起处理代码的手段

Using an interface in Java as a mean to work on a code with more teams

我在准备 Java OCA 考试时遇到了这个问题和答案。

Imagine you are working with another team to build an application. You are developing code that uses a class that the other team has not finished writing yet. Which element of Java would best facilitate this development, allowing easy integration once the other team’s code is complete?

A. An abstract class

B. An interface

我回答了A,但正确答案是B。

原因是:

The key here is understanding which of these features of Java allow one developer to build their application around another developer’s code, even if that code is not ready yet. For this problem, an interface is the best choice. If the two teams agree on a common interface, one developer can write code that uses the interface, while another developer writes code that implements the interface. Assuming neither team changes the interface, the code can be easily integrated once both teams are done. For these reasons, Option B is the correct answer.

我不明白如何在不实现接口的情况下使用它。

关键在 "one developer can write code that uses the interface",也就是说,您可以编写适用于实现此接口的 classes 实例的代码,并在实际上不知道 class 那些东西的情况下调用它们的方法实例也不会是任何可能破坏您的代码的实现细节。

因此,编写代码意味着您可以编译它,但除非提供实现,否则应用程序当然不会 运行。一种实现可能是模型,它对测试目的很有用,并且很难用抽象 classes 来实现。

为什么抽象 classes 在很多情况下是次等的选择?一个原因是 class 只能有 一个 直接超级 class 因此在实现时不能从多个独立的抽象 class 继承多个独立的接口很容易。除其他事项外,您还可以减少耦合,因为您不必将不相关的方法放入单个 class.

您不能编写摘要 class 因为您真的不想编写被丢弃的代码。另一个团队最终会交付它的 class,所以你在摘要 class 中付出的每一份努力很可能都是白费的。

实现一个干净的界面可以让你和其他团队很好地了解你需要什么,所以实现它应该是直截了当的。

您可以开发接口客户端代码(即 类 使用接口的人)参考接口的虚假实现(例如返回固定数据的实现),而其他开发人员则处理真实的接口实现并集成什么时候可以真正实现。您可以使用假实现来 运行 自动化测试和 运行 整个系统,或者使用 模拟库 来自动化测试。 如您所说,核心思想是 仅引用抽象(接口),以便可以 替代 实现 。接口是比抽象 类 更好的抽象,因为它们 只有抽象 性质(实际上抽象 类 可以有 具体 部分,接口不能)。