在 java 中不使用私有引用实现单例模式?
Implement singleton pattern without using a private reference in java?
最近的讨论中有人提出这个问题,但未能正确解决。但是我通过举 Enum
的例子来回答它,但他正在寻找其他方式。你能强调一下我们可以克服上述问题的方法吗?
简答?
使用一个 private YourClass
构造函数和一个 public YourClass
带有急切实例化的变量
长答案
https://en.wikipedia.org/wiki/Singleton_pattern
public class Singleton {
public static final Singleton INSTANCE = new Singleton();
//^ public variable
private Singleton() {}
//^ private constructor
}
这是个坏主意,但如果您将 private
变量更改为 public
变量,您将实现您的目标。您可能也应该将变量声明为 final
以避免意外,但这不是绝对必要的,也不是一个好主意(IMO)。
就其价值而言,没有办法实现不涉及显式变量来保存实例的单例,或者 enum
.
以下是 Bloch 关于 public 和私有变量方法之间权衡的看法:
"One advantage of the factory-method approach is that it gives you the flexibility to change your mind about whether the class should be a singleton without changing its API. The factory method returns the sole instance but could easily be modified to return, say, a unique instance for each thread that invokes it. A second advantage, concerning generic types, is discussed in Item 27. Often neither of these advantages is relevant, and the final-field approach is simpler."
我的论点是,知道您将来不需要改变主意涉及一定程度的先见之明。
或者换句话说,您无法知道:您只能预测。你的预测可能是错误的。如果该预测确实是错误的,那么您必须更改通过 public 变量访问单例的每一段代码。
现在,如果您的代码库很小,那么您需要更改的代码量就会受到限制。但是,如果您的代码库很大,或者不是您要更改所有代码,那么这种错误可能会造成严重后果。
这就是为什么这是个坏主意。
这就是您如何使用 public
字段实现 Singleton
:
public class Singleton {
public static final Singleton INSTANCE = new Singleton();
private Singleton() {}
}
进一步阅读此方法的优缺点:
Item 3 来自 Joshua Bloch 的 Effective Java.
最近的讨论中有人提出这个问题,但未能正确解决。但是我通过举 Enum
的例子来回答它,但他正在寻找其他方式。你能强调一下我们可以克服上述问题的方法吗?
简答?
使用一个 private YourClass
构造函数和一个 public YourClass
带有急切实例化的变量
长答案
https://en.wikipedia.org/wiki/Singleton_pattern
public class Singleton {
public static final Singleton INSTANCE = new Singleton();
//^ public variable
private Singleton() {}
//^ private constructor
}
这是个坏主意,但如果您将 private
变量更改为 public
变量,您将实现您的目标。您可能也应该将变量声明为 final
以避免意外,但这不是绝对必要的,也不是一个好主意(IMO)。
就其价值而言,没有办法实现不涉及显式变量来保存实例的单例,或者 enum
.
以下是 Bloch 关于 public 和私有变量方法之间权衡的看法:
"One advantage of the factory-method approach is that it gives you the flexibility to change your mind about whether the class should be a singleton without changing its API. The factory method returns the sole instance but could easily be modified to return, say, a unique instance for each thread that invokes it. A second advantage, concerning generic types, is discussed in Item 27. Often neither of these advantages is relevant, and the final-field approach is simpler."
我的论点是,知道您将来不需要改变主意涉及一定程度的先见之明。
或者换句话说,您无法知道:您只能预测。你的预测可能是错误的。如果该预测确实是错误的,那么您必须更改通过 public 变量访问单例的每一段代码。
现在,如果您的代码库很小,那么您需要更改的代码量就会受到限制。但是,如果您的代码库很大,或者不是您要更改所有代码,那么这种错误可能会造成严重后果。
这就是为什么这是个坏主意。
这就是您如何使用 public
字段实现 Singleton
:
public class Singleton {
public static final Singleton INSTANCE = new Singleton();
private Singleton() {}
}
进一步阅读此方法的优缺点:
Item 3 来自 Joshua Bloch 的 Effective Java.