懒汉式单例模式(DCL)
/** * 懒汉式 */ class Singleton { // 1、私有构造方法 private Singleton() {} // 2、私有静态实例 private static volatile Singleton instance; // 3、公有获取单例方法 public static Singleton getInstance() { if (null == instance) { synchronized (Singleton.class) { if (null == instance) { instance = new Singleton(); } } } return instance; } }
好处:第一次调用才初始化,避免了内存消耗
坏处:加锁,影响效率
饿汉式单例模式
/** * 饿汉式 */ class Singleton { // 1、私有构造方法 private Singleton() {} // 2、私有静态实例 private static Singleton instance = new Singleton(); // 3、公有获取单例方法 public static Singleton getInstance() { return instance; } }
好处:没有加锁,执行效率高
坏处:类加载时就初始化了,浪费内存
静态内部类单例模式
/** * 静态内部类单例(holder) */ class Singleton { // 1、私有构造方法 private Singleton() {} // 3、公有获取单例方法 public static Singleton getInstance() { return Holder.INSTANCE; } // 2、私有静态内部类生成单例 private static class Holder { private static final Singleton INSTANCE = new Singleton(); } }
好处:内部类只有在外部类被调用才加载,避免了浪费内存,又保证了线程安全