我应该针对接口还是抽象基 Class 进行编程?这句话到底是什么意思?

Should I Program to an Interface or an Abstract Base Class? What exactly does that phrase mean?

在面向对象编程中,我读到您应该针对接口而不是实现进行编程,但它们是指文字接口(根本没有共享代码)吗?

是否可以对抽象基础 class 进行编程,它本来是一个接口,除了这个 "interface" 中的变量,所有子 classes 都应该是有?在 sub-classes 之间复制变量会带来不便,因为如果我更改其中一个 sub-classes 中的一个变量的名称,我将不得不更改该变量的名称在所有子 classes 中。

按照 "program to an interface not an implementation" 的原则,这样可以吗?或者你会在抽象基础 class 之上创建另一个接口并针对该接口编程吗?

注意:C++ 没有接口。你可能会争辩说它不需要它们。

you should program to an interface not an implementation but do they mean literal interfaces (no shared code at all)?

可能吧。在这样做有意义的地方,它可以很好地工作。注意:在 Java 接口中也可以有代码。

Is it okay to program to an abstract base class that would have been an interface except that there were variables in this "interface" that all sub-classes were expected to have?

如果您需要实现中的字段,抽象 class 可能有意义。您仍然可以使用界面。

Replicating a variable across sub-classes would have been an inconvenience because if I changed the name of one of the variables in one of the sub-classes I would have to change the name of that variable in all of the sub-classes.

这是使用 IDE 的地方。您可以通过一个操作更改所有代码中的字段、class、方法名称。

is this okay or would you create another interface on top of the abstract base class and program to that interface?

您可以将实现编码为抽象 class,但该 class 的用户应该尽可能使用接口。

例如HashMap 扩展了 AbstractMap 但实现了 Map。大多数人会使用 Map 而不是 AbstractMap

您想对接口进行编程,因为这意味着更低的耦合度。请注意,Java 中的接口更灵活,因为它们可以由 class 层次结构中的 class anywhere 实现,这与抽象 class 不同es(作为单一继承的结果)。这种灵活性意味着您的代码可以更高程度地重用。

"programming to an interface not an implementation"的重点是上面提到的一般原则,即使它们可能会造成一些小的不便

此外,即使您针对一个接口编程,如果您愿意,您始终可以通过抽象 classes 实现所述接口(或其中的一部分),同时实现低耦合和代码可重用性同时

编写抽象甚至具体的 classes 总是可以的,但是如果你能避免它就更好了。

This discussion might be helpful or this one and of course this one.