我正在做一些关于单身人士的研究,特别是关于单身人士的懒惰与急切初始化.
急切初始化的一个例子:
public class Singleton
{
//initialzed during class loading
private static final Singleton INSTANCE = new Singleton();
//to prevent creating another instance of Singleton
private Singleton(){}
public static Singleton getSingleton(){
return INSTANCE;
}
}
Run Code Online (Sandbox Code Playgroud)
但如上所示,它是急切的初始化和线程安全留给jvm但现在,我希望有相同的模式,但延迟初始化.
所以我想出了这个方法:
public final class Foo {
private static class FooLoader {
private static final Foo INSTANCE = new Foo();
}
private Foo() {
if (FooLoader.INSTANCE != null) {
throw new IllegalStateException("Already instantiated");
}
}
public static Foo getInstance() {
return FooLoader.INSTANCE;
}
}
Run Code Online (Sandbox Code Playgroud)
如上图所示 …
public static MySingleton getInstance() {
if (_instance==null) {
synchronized (MySingleton.class) {
_instance = new MySingleton();
}
}
return _instance;
}
Run Code Online (Sandbox Code Playgroud)
1.上述getInstance方法的实现存在缺陷吗?2.这两种实现有什么区别.
public static synchronized MySingleton getInstance() {
if (_instance==null) {
_instance = new MySingleton();
}
return _instance;
}
Run Code Online (Sandbox Code Playgroud)
我已经在stackoverflow中看到了很多关于单例模式的答案,但我发布的问题是在这种特殊情况下主要知道方法和块级别的'synchronize'的区别.