1、单例模式的几种写法
懒汉模式
public class Singleton { private static Singleton instance = null; private Singleton(){} public static synchronized Singleton getInstance(){ //如果还没有被实例化过,就实例化一个,然后返回 if(instance == null){ instance = new Singleton(); } return instance; } }
饿汉模式
public class Singleton { //类加载的时候instance就已经指向了一个实例 private static Singleton instance = new Singleton(); private Singleton(){} public static Singleton getInstance(){ return instance; } }
双重检验锁
public class Singleton { private static Singleton instance = null; private Singleton(){} public static Singleton getInstance(){ if(instance == null){ synchronized (Singleton.class){ if(instance == null){ instance = new Singleton(); } } } return instance; } }