1.饿汉式
简单、线程安全;但静态对象一直存在,占内存
public class SingletonTest {
private static final SingletonTest instance = new SingletonTest();
private SingletonTest() {
}
public static SingletonTest getInstancei() {
return instance;
}
}
2.饱汉式 较饿汉式相对节约内存,调用方法时才会去创建实例;但线程不安全
public class SingletonTest {
private SingletonTest() {
}
private static SingletonTest instance;
public static SingletonTest getInstance() {
if (instance == null)
instance = new SingletonTest();
return instance;
}
}
3.饱汉式(优化1)
简单粗暴解决线程安全问题;但是效率较低
public class SingletonTest {
private SingletonTest() {
}
//这里的volatile保证new SingletonTest()时的顺序性
private static volatile SingletonTest instance;
public static synchronized SingletonTest getInstance() {
if (instance == null)
instance = new SingletonTest();
return instance;
}
}
4.饱汉式(优化2)
效率相对提升
public class SingletonTest {
private SingletonTest() {
}
//这里的volatile保证new SingletonTest()时的顺序性
private static volatile SingletonTest instance;
public static SingletonTest getIstance() {
if (instance == null) {
synchronized (SingletonTest.class) {
if (instance == null) {
instance = new SingletonTest();
}
}
}
return instance;
}
}
4.静态内部枚举类(推荐)
public class EnumSingleton{
private EnumSingleton(){}
public static EnumSingleton getInstance(){
return Singleton.INSTANCE.getInstance();
}
private static enum Singleton{
INSTANCE;
private EnumSingleton singleton;
//JVM会保证此方法绝对只调用一次
private Singleton(){
singleton = new EnumSingleton();
}
public EnumSingleton getInstance(){
return singleton;
}
}
}