饿汉模式
public class Singleton {//实例化private static Singleton instance=new Singleton();private Singleton() { if(instance!=null){ throw new RuntimeException("已经存在实例"); }System.out.println("Singleton is create");}//获取实例的方法public static Singleton getInstance() {return instance;}}
懒汉模式
public class Singleton {//实例化private static Singleton instance=null;private Singleton() { if(instance!=null){ //防止反射破坏单例 throw new RuntimeException("已经存在实例"); }System.out.println("Singleton is create");}//获取实例的方法public static Singleton getInstance() {if(instance==null) {instance=new Singleton();}return instance;}}
DCL(双端检索)
public class Singleton {//实例化private static volatile Singleton instance=null;private Singleton() { if(instance!=null){ throw new RuntimeException("已经存在实例"); }System.out.println("Singleton is create");}//获取实例的方法public static Singleton getInstance() {if(instance == null) {synchronized(Singleton.class) {if(instance == null) {instance=new Singleton();}}}return instance;}}