从 Java 8 开始,我们可以在接口(interface)中使用默认方法和静态方法。
常量接口(interface)模式是对接口(interface)的不良使用,称为常量接口(interface)反模式。
>Effective Java , 第 17 项:
The constant interface pattern is a poor use of interfaces. That a class uses some constants internally is an implementation detail. Implementing a constant interface causes this implementation detail to leak into the class's exported API. It is of no consequence to the users of a class that the class implements a constant interface. In fact, it may even confuse them. Worse, it represents a commitment: if in a future release the class is modified so that it no longer needs to use the constants, it still must implement the interface to ensure binary compatibility. If a nonfinal class implements a constant interface, all of its subclasses will have their namespaces polluted by the constants in the interface.
There are several constant interfaces in the java platform libraries, such as java.io.ObjectStreamConstants. These interfaces should be regarded as anomalies and should not be emulated.
如果使用常量接口(interface)是一种不好的做法,那么什么时候使用接口(interface)静态方法就可能成为一种不好的做法?
最佳答案
常量接口(interface)的主要问题不是包含大量常量的接口(interface)。
当类实现该接口(interface)时,它们就可以更轻松地访问常量:
public interface Foo {
public static final int CONSTANT = 1;
}
public class NotOkay implements Foo {
private int value = CONSTANT;
}
public class Okay {
private int value = Foo.CONSTANT;
}
Class NotOkay
不仅在接口(interface) Foo
和它本身之间创建了一个虚假的关系(那里真的没有什么可实现的),而且常量值成为其公共(public)的一部分API。
(在 Java 5 中引入 static import
之前,这种做法更为常见。)
对于静态接口(interface)方法,实现接口(interface)真的没有意义,因为您不能以相同的方式访问它们:静态接口(interface)方法不是继承的。
关于Java 8 : When the use of Interface static methods becomes a bad practice?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31598776/