接口与单例中的全局变量

Global variables in Interface vs Singleton

我需要几个全局变量(例如:数据库名称),它们将在我的程序中被其他 classes 使用。

我可以创建一个包含变量的单例 class,但我发现我也可以简单地创建一个包含变量的接口(没有任何方法)。由于接口中的变量是静态的和最终的,这似乎是一个干净的实现。

我读到认为在接口中声明变量是糟糕的设计,那么为什么会这样?创建全局变量的最佳方法是什么?

根据 Sonar rule:

,仅使用接口来保存常量是一种代码味道

Constants should not be defined in interfaces (squid:S1214)

According to Joshua Bloch, author of "Effective Java": 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.