来自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; } }
是final
上class Singleton
和private
上Singleton()
彼此冗余?
只有其中一个就足够了吗?
谢谢。
最佳答案
一般来说,这两个关键字并不“彼此冗余”。也就是说,它们有不同的效果。
将Singleton
声明为final
意味着它不能被子类化。将其构造函数声明为private
意味着它不能被其他人实例化。后者通常是您执行单例模式所需的。
但是,正如OP在我的答案初稿的评论中指出的那样,将构造函数声明为private
确实可以防止在这种情况下进行子类化。这是因为子类没有其他可用的构造函数。因此,在这种情况下,将类声明为 final
是不必要的。但是,如果有另一个构造函数声明为 protected ,则可以创建子类。
关于java - `final` 上的 `class Singleton` 和 `private` 上的 `Singleton()` 是否彼此冗余?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46480469/