-
懒汉模式-适合单线程环境
/** * 单例模式 懒汉模式-适合单线程环境 */ public class Singleton { private static Singleton instance = null; private Singleton(){ } public static Singleton getInstance(){ if (instance == null) { instance = new Singleton(); } return instance; } }
- 懒汉模式-加入锁保证同步
/** * 单例模式 懒汉模式-适合多线程环境 */ public class Singleton { private static Singleton instance = null; private Singleton(){ } /** * 加入了锁 会影响效率,耗时 * @return */ public static synchronized Singleton getInstance(){ if (instance == null) { instance = new Singleton(); } return instance; } }
- 懒汉模式-多线程环境效率优化
/** * 单例模式 懒汉模式-多线程环境效率优化 */ public class Singleton { private static Singleton instance = null; private Singleton(){ } /** * 加锁之前,进行判断 * @return */ public static Singleton getInstance(){ if (instance == null) { synchronized(Singleton.class){ if (instance == null) { instance = new Singleton(); } } } return instance; } }
- 饿汉模式
/** * 单例模式 饿汉模式 */ public class Singleton { private static Singleton instance = new Singleton(); private Singleton(){ } /** * 没有lazy loading的效果,从而降低内存的使用率。 * @return */ public static Singleton getInstance(){ return instance; } }
- 静态内部类实现
/** * 单例模式 静态内部类实现 */ public class Singleton { private Singleton(){ } /** * 静态内部类 只有在Singleton实例化时,才会实例化 */ private static class SingletonHolder{ private final static Singleton INSTANCE = new Singleton(); } public static Singleton getInstance(){ return SingletonHolder.INSTANCE; } }
- 双重校验实现
public class Singleton { public Singleton() { } private volatile static Singleton instance; public Singleton getInstance() { if (instance == null) { synchronized (Singleton.class) { if (instance == null) { instance = new Singleton(); } } } return instance; } }