单例模式

单线程环境

饿汉式:通过静态常量、静态代码块实现,线程同步

懒汉式:判断null之后再new对象,线程不同步

静态内部类

线程安全,延迟加载,效率高

仅当调用getInstance()方法时,静态内部类才进行加载,加载遵循双亲委派模式,加载过程线程安全

 1  2  3  4  5  6  7  8  9 10 11 12
public class Singleton { private Singleton() { } private static class SingletonInstance { private static final Singleton INSTANCE = new Singleton(); } public static Singleton getInstance() { return SingletonInstance.INSTANCE; } }

双重检查

线程安全,延迟加载,效率高

 1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18
public class Singleton { private static volatile Singleton singleton; private Singleton() { } public static Singleton getInstance() { if (singleton == null) { synchronized (Singleton.class) { if (singleton == null) { singleton = new Singleton(); } } } return singleton; } }

浙ICP备11005866号-8