根据我的理解,Singleton是在应用程序生命周期中持续存在的类的单个实例。然而,我看到了一些不同的系统实现,但我总是被告知它们是错误的、有缺陷的等等。我将发布我更常见的两个,我想听听基于哪个实现更好以及为什么更好的意见/事实。实现是可编译的。
实施A:
public class Foo {
private static Foo singelton;
private Foo() {
System.out.println("Bar");
}
public static Foo getSingleton() {
if(singleton == null) singleton = new Foo();
return singleton;
}
public static void main(String[] args) {
Foo.getSingleton();
}
}
实施B:
public class Foo {
private static final Foo singelton = new Foo();
private Foo() {
if(singelton != null) {
throw new IllegalStateException("Singleton class was already constructed.");
}
System.out.println("Bar");
}
public static void main(String[] args) {
// NOT REQUIRED
}
}
您将在实现B中注意到Singleton实例是最终实例。此外,由于是静态实现,main(String[])
方法从不需要构造此类的实例。
实施方案A和B将产生相同的结果。
意见?
嘿,您已经展示了两个实现,第二个称为早期初始化,第一个称为延迟初始化,因为它只是根据需要初始化类。但是,您的第一次初始化将在多线程环境中失败。您必须使用双重检查锁定来保护您的代码。例如:
public class EagerSingleton {
private static volatile EagerSingleton instance = null;
// private constructor
private EagerSingleton() {
}
public static EagerSingleton getInstance() {
if (instance == null) {
synchronized (EagerSingleton.class) {
// Double check
if (instance == null) {
instance = new EagerSingleton();
}
}
}
return instance;
}
}
有关更多详细信息,请查看:http://howtodoinjava.com/2012/10/22/singleton-design-pattern-in-java/