单例模式的几种套路 发表于 2017-03-01 | | 阅读次数 套路1 - 立即加载 instantly initialization1234567891011public class EagerSingleton { **private** **static** EagerSingleton instance = new EagerSingleton(); **private** EagerSingleton() { } public static EagerSingleton getInstance() { return instance; }} 套路2 - 延迟初始化 lazy initialization1234567891011121314151617181920public class LazySingleton { private static LazySingleton instance; private LazySingleton() { } public static **synchronized** LazySingleton getInstance() { if (instance == null) { try { Thread.sleep(1000 * 3);// mock long time init } catch (InterruptedException e) { e.printStackTrace(); } instance = new LazySingleton(); } return instance; }} 套路3 - 静态内部类 static Holder1234567891011121314151617181920public class InnerHolderClass { private InnerHolderClass() { } private static class InnerHolder { static InnerHolderClass innerHolder = new InnerHolderClass(); } public static InnerHolderClass getInstance() { InnerHolderClass innerHolder = InnerHolder.innerHolder; try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } return innerHolder; }} 套路4 - 枚举 enum123public enum EnumSingleton { SINGLE;} 套路5 - 双重锁 double check123456789101112131415161718192021public class DoubleCheckSingleton { //volatile is important!!! //volatile is important!!! //volatile is important!!! private static **volatile** DoubleCheckSingleton instance;//volatile is important!!! private DoubleCheckSingleton() { } public static DoubleCheckSingleton getInstance() { if (null == instance) { synchronized (DoubleCheckSingleton.class) { if (null == instance) { instance = new DoubleCheckSingleton(); } } } return instance; }} 12345678910111213141516171819202122public class EnhancedDoubleCheckSingleton { private static EnhancedDoubleCheckSingleton instance; private EnhancedDoubleCheckSingleton() { } //it's not the recommend way.we recommend lazy initialization inner class because the static instance field. public static EnhancedDoubleCheckSingleton getInstance() { **EnhancedDoubleCheckSingleton tmp = instance;** if (null == tmp) { synchronized (EnhancedDoubleCheckSingleton.class) { **tmp = instance;** if (null == tmp) { instance = tmp = new EnhancedDoubleCheckSingleton(); } } } return tmp; }}