java - `final` 上的 `class Singleton` 和 `private` 上的 `Singleton()` 是否彼此冗余?

标签 java design-patterns singleton

来自https://en.wikipedia.org/wiki/Singleton_pattern#Implementation

An implementation of the singleton pattern must:

  • ensure that only one instance of the singleton class ever exists; and
  • provide global access to that instance.

Typically, this is done by:

  • declaring all constructors of the class to be private; and
  • providing a static method that returns a reference to the instance.

The instance is usually stored as a private static variable; the instance is created when the variable is initialized, at some point before the static method is first called. The following is a sample implementation written in Java.

public final class Singleton {
    private static final Singleton INSTANCE = new Singleton();

    private Singleton() {}

    public static Singleton getInstance() {
        return INSTANCE;
    }
}

finalclass SingletonprivateSingleton()彼此冗余?

只有其中一个就足够了吗?

谢谢。

最佳答案

一般来说,这两个关键字并不“彼此冗余”。也就是说,它们有不同的效果。

Singleton声明为final意味着它不能被子类化。将其构造函数声明为private意味着它不能被其他人实例化。后者通常是您执行单例模式所需的。

但是,正如OP在我的答案初稿的评论中指出的那样,将构造函数声明为private确实可以防止在这种情况下进行子类化。这是因为子类没有其他可用的构造函数。因此,在这种情况下,将类声明为 final 是不必要的。但是,如果有另一个构造函数声明为 protected ,则可以创建子类。

关于java - `final` 上的 `class Singleton` 和 `private` 上的 `Singleton()` 是否彼此冗余?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46480469/

相关文章:

Java Noob 创建自定义方法来打印数组并计算持续时间

java - 通过实体图加载元素集合时,SqlNode 的文本未引用预期的列数错误

c++ - 创建派生类的模式,派生类本身和基类都包含许多字段

c++ - 纯虚函数重载

java - 单例中的双重检查锁定

c++ - 如何创建基类的单个实例

java - 使用 Jackson 从 ObjectNode 获取嵌套的 JSON 元素

Java:如何替换数组中的字符串元素

c# - 如何在执行期间暂停、保存状态并稍后从同一点继续?

C++单例实现STL线程安全