为什么创建接口而不是每个类的实现

为什么创建接口而不是每个类的实现

本文介绍了为什么创建接口而不是每个类的实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

它似乎是标准所以我到目前为止一直在使用它,但现在我正在从头开始构建一个新类而不是修改旧类,并且我觉得我应该理解为什么我应该遵循项目约定。

It seems to be the standard so I have been going along with it so far, but now I am building a new class from scratch instead of modifying the old ones and feel I should understand why I should follow the projects convention.

几乎每个类都有一个接口,称为 classnameable 。在代码 database.class 中永远不会出现一次,但在我希望使用该类的地方,我看到 databaseable.class

Almost every class has an interface to it which is called classnameable. In the code database.class would never appear even once but in place where I would want to use that class I see databaseable.class.

据我所知,一个接口是一个从未实现过但却无法保持标准的类。那么为什么接口被用作真正的类?

To my understanding an interface was a class that was never implemented but was inhereted from to keep standards. So why are the interfaces being used as if they were real classes?

推荐答案

这有点困惑。接口定义API,以便来自不同作者,模块或项目的代码片段可以进行交互。例如, java.util.Collections.sort()可以对实现 List 接口的任何内容进行排序,并包含对象实现 Comparable 接口 - 即使编写排序代码时实现类可能还不存在!

This is a bit confused. An interface defines an API, so that pieces of code from different authors, modules or projects can interact. For example, java.util.Collections.sort() can sort anything that implements the List interface and contains objects that implement the Comparable interface - even though the implementation classes may not have existed yet when the sorting code was written!

现在你的项目中的情况似乎反映了一个不幸的相当常见的反模式:拥有所有的接口,主要是一个实现类,甚至是内部类。

Now the situation in your project seems to reflect an unfortunately rather common antipattern: having an interface for everything, mostly with a single implementation class, even for internal classes.

过去,测试驱动开发(TDD)的支持者强烈推动这一点,他们认为能够独立测试每个类及其所有依赖项是至关重要的由mock对象替换。较旧的模拟框架只能模拟接口,因此为了能够单独测试每个类,所有类间依赖关系都必须通过接口。

This used to be strongly promoted by proponents of Test-Driven-Development (TDD) who see it as vital to be able to test every class in isolation with all its dependencies replaced by mock objects. Older mocking frameworks could only mock interfaces, so to be able to test every class in isolation, all inter-class dependencies had to be through interfaces.

幸运的是,更新的模拟框架可以模拟具体类,并且不要求您使用不必要的接口污染您的项目。有些人可能仍会争辩说无论如何都应该减少耦合,但IMO他们只是合理化他们不改变他们的做法的愿望。

Fortunately, newer mocking frameworks can mock concrete classes and don't require you to pollute your project with unnecessary interfaces. Some people will probably still argue that it should be done anyway to "reduce coupling", but IMO they're just rationalizing their desire not to change their practices.

当然,如果你不做原教旨主义TDD,那么从来没有一个很好的理由为所有东西建立一个接口 - 但是有很好的理由为某些接口提供接口事情。

And of course, if you don't do fundamentalist TDD, there never was a good reason to have an interface for everything - but very good reasons to have interfaces for some things.

这篇关于为什么创建接口而不是每个类的实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 09:15