单例模式可以说是设计模式中最简单的一种了,虽然简单,但是用处却是很大的。我在日常工作中用到最多的就是单例模式了,单例模式几乎也是面试必问的。
目录
private Singleton(){} private static Singleton singleton = null ;//懒汉模式 //静态工厂方法 public static Singleton getInstance(){ if(singleton == null){ singleton = new Singleton(); } return singleton; } |
private Singleton(){} private static Singleton singleton = null ;//懒汉模式 public static Singleton getInstance1(){ if(singleton == null){ synchronized (Singleton.class) { if (singleton == null) { singleton = new Singleton(); } } } return singleton; } |
private Singleton(){}
//jvm编译器的指令重排 private volatile static Singleton singleton = null ;//懒汉模式 public static Singleton getInstance1(){ if(singleton == null){ synchronized (Singleton.class) { if (singleton == null) { singleton = new Singleton(); } } } return singleton; } |
//静态内部类:利用classloader的加载机制来实现懒加载 private static class LazyHolder{ private static final Singleton INSTANCE = new Singleton(); }
private Singleton(){}
public static Singleton getInstance (){ return LazyHolder.INSTANCE; } |
单例模式实现 | 是否线程安全 | 是否懒加载 | 是否防止反射构建 |
双重锁检测 | 是 | 是 | 否 |
静态内部类 | 是 | 是 | 否 |
枚举 | 是 | 否 | 是 |