懒汉(线程不安全)
public class Singleton{
private static Singleton instance;
private static Singleton(){}
public static Singleton getInstance(){
if(instance==null)
instance=new Singleton();
return instance;
}
懒汉(线程安全)
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 static Singleton instance=null;
static{
instance=new Singleton();
}
private Singleton(){}
public static Singleton getInstance(){
return instance;
}
}
静态内部类
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 Singleton{
instance;
Singleton(){
instance=Singleton();
}
public void 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();
}
}
}
}