thread safe Singleton 的几种方法?# Java - 爪哇娇娃
s*e
1 楼
方法1:
最简单的 public static synchronized getInstance()
方法2:
一次面试中,面试官让我再举出一种方法,我取出了用 inner class 的方法, 以前在
wiki 上看到的:
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
http://en.wikipedia.org/wiki/Singleton_pattern
但是面试官说这种方法是错的~~~~~~~~
方法3:
貌似还有一种方法是:
public class Singleton {
public final static Singleton INSTANCE = new Singleton();
private Singleton() {
最简单的 public static synchronized getInstance()
方法2:
一次面试中,面试官让我再举出一种方法,我取出了用 inner class 的方法, 以前在
wiki 上看到的:
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
http://en.wikipedia.org/wiki/Singleton_pattern
但是面试官说这种方法是错的~~~~~~~~
方法3:
貌似还有一种方法是:
public class Singleton {
public final static Singleton INSTANCE = new Singleton();
private Singleton() {