我正在阅读维基百科上的Singleton文章,我遇到了这个例子:
public class Singleton {
// Private constructor prevents instantiation from other classes
private Singleton() {}
/**
* SingletonHolder is loaded on the first execution of Singleton.getInstance()
* or the first access to SingletonHolder.INSTANCE, not before.
*/
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
Run Code Online (Sandbox Code Playgroud)
虽然我非常喜欢这个Singleton的行为方式,但我看不出如何调整它以将参数合并到构造函数中.在Java中执行此操作的首选方法是什么?我必须这样做吗?
public class Singleton
{
private static Singleton singleton = null;
private final int x;
private Singleton(int x) {
this.x …Run Code Online (Sandbox Code Playgroud)