1 懒汉模式
public class Singleton {
private Singleton singleton = null;
private Singleton() {
}
public Singleton getInstance() {
if (singleton == null) {
singleton = new Singleton();
} else {
return singleton;
}
}
}
问题在于不是线程安全的。要线程安全,在getInstance前面加上synchronized关键字即可,但是开销太大。
2 饿汉模式
public class Singleton {
private Singleton singleton = new Singleton();
private Singleton() {
}
public Singletion getSingleton() {
return singleton;
}
}
3 静态内部类
public class Singleton {
private static class SingletonHolder {
private static Singleton instance = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.instance;
}
}