单例模式的五种实现写法:懒汉、饿汉、双重检验锁、静态内部类、枚举。线程安全的实现方式
懒汉式:
public class Singleton {
private static Singleton instatnce;
private Singleton(){}
public static synchronized Singleton getInstance(){
if(instatnce == null)
instatnce=new Singleton();
return instatnce;
}
}
双重检验锁:
public class Singleton {
private static Singleton instatnce;
private Singleton(){}
public static Singleton getInstance(){
if(instatnce == null){
synchronized(Singleton.class){
if(instatnce == null)
instatnce=new Singleton();
}
}
return instatnce;
}
}
饿汉式:
public class Singleton {
private static Singleton instatnce=new Singleton();
private Singleton(){}
public static Singleton getInstance(){
return instatnce;
}
}
静态内部类:
public class Singleton {
private static class SingletonHolder{
private static final Singleton INSTANCE = new Singleton();
}
private Singleton(){}
public static final Singleton getInstance(){
return SingletonHolder.INSTANCE;
}
}
枚举:
public enum EasySingleton {
INSTANCE;
}