//懒汉式
public class Singleton{
private static Singleton uniqueInstance=null;
private Singleton(){
}
public static synchronized Singleton getInstance(){
if(uniqueInstance==null){
uniqueInstance=new Singleton();
}
return uniqueInstance;
}
}
//懒汉式 volatile
public class Singleton{
private volatile static Singleton instance=null;
private Singleton(){
}
public static Singleton getInstance(){
if(instance==null){
synchronized(Singleton.class){
if(instance==null){
instance=new Singleton();
}
}
}
return instance;
}
}
//饿汉式
public class Singleton{
private static Singleton uniqueInstance=new Singleton();
private Singleton(){
}
public static Singleton getInstance(){
return uniqueInstance;
}
}
//内部类
public class Singleton{
public static class SingletonHolder{
private static Singleton instance = new Singleton();
}
private Singleton(){
}
public static Singleton getInstance(){
return SingletonHolder.instance;
}
}
//枚举
public enum Singleton{
uniqueInstance;
}