Java单例模式的实现方法有以下几种:
public class Singleton {
private static Singleton instance;
private Singleton(){}
public static Singleton getInstance(){
if(instance == null){
instance = new Singleton();
}
return instance;
}
}
可以通过在getInstance()
方法上加锁synchronized
来实现线程安全的懒汉式单例模式,但是会影响效率:
public class Singleton {
private static Singleton instance;
private Singleton(){}
public static synchronized Singleton getInstance(){
if(instance == null){
instance = new Singleton();
}
return instance;
}
}
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton(){}
public static Singleton getInstance(){
return instance;
}
}
由于在类加载时就创建实例,因此无法实现延迟加载。
public class Singleton {
private volatile static Singleton instance;
private Singleton(){}
public static Singleton getInstance(){
if(instance == null){
synchronized (Singleton.class){
if(instance == null){
instance = new Singleton();
}
}
}
return instance;
}
}
使用volatile
修饰instance
变量可以保证多线程环境下的可见性和有序性。
public class Singleton {
private Singleton(){}
private static class SingletonHolder{
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance(){
return SingletonHolder.INSTANCE;
}
}
静态内部类只有在第一次使用时才会被加载,从而实现了延迟加载。
public enum Singleton {
INSTANCE;
public void doSomething(){
// do something
}
}